No Description

Utils.cs 45KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using System.Web;
  8. using System.Configuration;
  9. using System.Collections.Specialized;
  10. using System.Reflection;
  11. using System.ComponentModel;
  12. namespace CallCenterApi.Common
  13. {
  14. public static class Utils
  15. {
  16. #region 对象转换处理
  17. /// <summary>
  18. /// 判断对象是否为Int32类型的数字
  19. /// </summary>
  20. /// <param name="Expression"></param>
  21. /// <returns></returns>
  22. public static bool IsNumeric(object expression)
  23. {
  24. if (expression != null)
  25. return IsNumeric(expression.ToString());
  26. return false;
  27. }
  28. /// <summary>
  29. /// 判断对象是否为Int32类型的数字
  30. /// </summary>
  31. /// <param name="Expression"></param>
  32. /// <returns></returns>
  33. public static bool IsNumeric(string expression)
  34. {
  35. if (expression != null)
  36. {
  37. string str = expression;
  38. if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$"))
  39. {
  40. if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))
  41. return true;
  42. }
  43. }
  44. return false;
  45. }
  46. /// <summary>
  47. /// 是否为Double类型
  48. /// </summary>
  49. /// <param name="expression"></param>
  50. /// <returns></returns>
  51. public static bool IsDouble(object expression)
  52. {
  53. if (expression != null)
  54. return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$");
  55. return false;
  56. }
  57. /// <summary>
  58. /// 将字符串转换为数组
  59. /// </summary>
  60. /// <param name="str">字符串</param>
  61. /// <returns>字符串数组</returns>
  62. public static string[] GetStrArray(string str)
  63. {
  64. return str.Split(new char[',']);
  65. }
  66. /// <summary>
  67. /// 将数组转换为字符串
  68. /// </summary>
  69. /// <param name="list">List</param>
  70. /// <param name="speater">分隔符</param>
  71. /// <returns>String</returns>
  72. public static string GetArrayStr(List<string> list, string speater)
  73. {
  74. StringBuilder sb = new StringBuilder();
  75. for (int i = 0; i < list.Count; i++)
  76. {
  77. if (i == list.Count - 1)
  78. {
  79. sb.Append(list[i]);
  80. }
  81. else
  82. {
  83. sb.Append(list[i]);
  84. sb.Append(speater);
  85. }
  86. }
  87. return sb.ToString();
  88. }
  89. /// <summary>
  90. /// 字符串数组转字符串List
  91. /// </summary>
  92. /// <param name="strArray"></param>
  93. /// <returns></returns>
  94. public static List<string> StrArrayToList(string[] strArray)
  95. {
  96. List<string> list = new List<string>();
  97. foreach (string s in strArray)
  98. {
  99. list.Add(s);
  100. }
  101. return list;
  102. }
  103. /// <summary>
  104. /// object型转换为bool型
  105. /// </summary>
  106. /// <param name="strValue">要转换的字符串</param>
  107. /// <param name="defValue">缺省值</param>
  108. /// <returns>转换后的bool类型结果</returns>
  109. public static bool StrToBool(object expression, bool defValue)
  110. {
  111. if (expression != null)
  112. return StrToBool(expression, defValue);
  113. return defValue;
  114. }
  115. /// <summary>
  116. /// string型转换为bool型
  117. /// </summary>
  118. /// <param name="strValue">要转换的字符串</param>
  119. /// <param name="defValue">缺省值</param>
  120. /// <returns>转换后的bool类型结果</returns>
  121. public static bool StrToBool(string expression, bool defValue)
  122. {
  123. if (expression != null)
  124. {
  125. if (string.Compare(expression, "true", true) == 0)
  126. return true;
  127. else if (string.Compare(expression, "false", true) == 0)
  128. return false;
  129. }
  130. return defValue;
  131. }
  132. /// <summary>
  133. /// 将对象转换为Int32类型
  134. /// </summary>
  135. /// <param name="expression">要转换的字符串</param>
  136. /// <param name="defValue">缺省值</param>
  137. /// <returns>转换后的int类型结果</returns>
  138. public static int ObjToInt(object expression, int defValue)
  139. {
  140. if (expression != null)
  141. return StrToInt(expression.ToString(), defValue);
  142. return defValue;
  143. }
  144. /// <summary>
  145. /// 将字符串转换为Int32类型
  146. /// </summary>
  147. /// <param name="expression">要转换的字符串</param>
  148. /// <param name="defValue">缺省值</param>
  149. /// <returns>转换后的int类型结果</returns>
  150. public static int StrToInt(string expression, int defValue)
  151. {
  152. if (string.IsNullOrEmpty(expression) || expression.Trim().Length >= 11 || !Regex.IsMatch(expression.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))
  153. return defValue;
  154. int rv;
  155. if (Int32.TryParse(expression, out rv))
  156. return rv;
  157. return Convert.ToInt32(StrToFloat(expression, defValue));
  158. }
  159. /// <summary>
  160. /// Object型转换为decimal型
  161. /// </summary>
  162. /// <param name="strValue">要转换的字符串</param>
  163. /// <param name="defValue">缺省值</param>
  164. /// <returns>转换后的decimal类型结果</returns>
  165. public static decimal ObjToDecimal(object expression, decimal defValue)
  166. {
  167. if (expression != null)
  168. return StrToDecimal(expression.ToString(), defValue);
  169. return defValue;
  170. }
  171. /// <summary>
  172. /// string型转换为decimal型
  173. /// </summary>
  174. /// <param name="strValue">要转换的字符串</param>
  175. /// <param name="defValue">缺省值</param>
  176. /// <returns>转换后的decimal类型结果</returns>
  177. public static decimal StrToDecimal(string expression, decimal defValue)
  178. {
  179. if ((expression == null) || (expression.Length > 10))
  180. return defValue;
  181. decimal intValue = defValue;
  182. if (expression != null)
  183. {
  184. bool IsDecimal = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
  185. if (IsDecimal)
  186. decimal.TryParse(expression, out intValue);
  187. }
  188. return intValue;
  189. }
  190. /// <summary>
  191. /// Object型转换为float型
  192. /// </summary>
  193. /// <param name="strValue">要转换的字符串</param>
  194. /// <param name="defValue">缺省值</param>
  195. /// <returns>转换后的int类型结果</returns>
  196. public static float ObjToFloat(object expression, float defValue)
  197. {
  198. if (expression != null)
  199. return StrToFloat(expression.ToString(), defValue);
  200. return defValue;
  201. }
  202. /// <summary>
  203. /// string型转换为float型
  204. /// </summary>
  205. /// <param name="strValue">要转换的字符串</param>
  206. /// <param name="defValue">缺省值</param>
  207. /// <returns>转换后的int类型结果</returns>
  208. public static float StrToFloat(string expression, float defValue)
  209. {
  210. if ((expression == null) || (expression.Length > 10))
  211. return defValue;
  212. float intValue = defValue;
  213. if (expression != null)
  214. {
  215. bool IsFloat = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");
  216. if (IsFloat)
  217. float.TryParse(expression, out intValue);
  218. }
  219. return intValue;
  220. }
  221. /// <summary>
  222. /// 将对象转换为日期时间类型
  223. /// </summary>
  224. /// <param name="str">要转换的字符串</param>
  225. /// <param name="defValue">缺省值</param>
  226. /// <returns>转换后的int类型结果</returns>
  227. public static DateTime StrToDateTime(string str, DateTime defValue)
  228. {
  229. if (!string.IsNullOrEmpty(str))
  230. {
  231. DateTime dateTime;
  232. if (DateTime.TryParse(str, out dateTime))
  233. return dateTime;
  234. }
  235. return defValue;
  236. }
  237. /// <summary>
  238. /// 将对象转换为日期时间类型
  239. /// </summary>
  240. /// <param name="str">要转换的字符串</param>
  241. /// <returns>转换后的int类型结果</returns>
  242. public static DateTime StrToDateTime(string str)
  243. {
  244. return StrToDateTime(str, DateTime.Now);
  245. }
  246. /// <summary>
  247. /// 将对象转换为日期时间类型
  248. /// </summary>
  249. /// <param name="obj">要转换的对象</param>
  250. /// <returns>转换后的int类型结果</returns>
  251. public static DateTime ObjectToDateTime(object obj)
  252. {
  253. return StrToDateTime(obj.ToString());
  254. }
  255. /// <summary>
  256. /// 将对象转换为日期时间类型
  257. /// </summary>
  258. /// <param name="obj">要转换的对象</param>
  259. /// <param name="defValue">缺省值</param>
  260. /// <returns>转换后的int类型结果</returns>
  261. public static DateTime ObjectToDateTime(object obj, DateTime defValue)
  262. {
  263. return StrToDateTime(obj.ToString(), defValue);
  264. }
  265. /// <summary>
  266. /// 将对象转换为字符串
  267. /// </summary>
  268. /// <param name="obj">要转换的对象</param>
  269. /// <returns>转换后的string类型结果</returns>
  270. public static string ObjectToStr(object obj)
  271. {
  272. if (obj == null)
  273. return "";
  274. return obj.ToString().Trim();
  275. }
  276. #endregion
  277. #region 分割字符串
  278. /// <summary>
  279. /// 分割字符串
  280. /// </summary>
  281. public static string[] SplitString(string strContent, string strSplit)
  282. {
  283. if (!string.IsNullOrEmpty(strContent))
  284. {
  285. if (strContent.IndexOf(strSplit) < 0)
  286. return new string[] { strContent };
  287. return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
  288. }
  289. else
  290. return new string[0] { };
  291. }
  292. /// <summary>
  293. /// 分割字符串
  294. /// </summary>
  295. /// <returns></returns>
  296. public static string[] SplitString(string strContent, string strSplit, int count)
  297. {
  298. string[] result = new string[count];
  299. string[] splited = SplitString(strContent, strSplit);
  300. for (int i = 0; i < count; i++)
  301. {
  302. if (i < splited.Length)
  303. result[i] = splited[i];
  304. else
  305. result[i] = string.Empty;
  306. }
  307. return result;
  308. }
  309. #endregion
  310. #region 删除最后结尾的一个逗号
  311. /// <summary>
  312. /// 删除最后结尾的一个逗号
  313. /// </summary>
  314. public static string DelLastComma(string str)
  315. {
  316. return str.Substring(0, str.LastIndexOf(","));
  317. }
  318. #endregion
  319. #region 删除最后结尾的指定字符后的字符
  320. /// <summary>
  321. /// 删除最后结尾的指定字符后的字符
  322. /// </summary>
  323. public static string DelLastChar(string str, string strchar)
  324. {
  325. if (string.IsNullOrEmpty(str))
  326. return "";
  327. if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1)
  328. {
  329. return str.Substring(0, str.LastIndexOf(strchar));
  330. }
  331. return str;
  332. }
  333. #endregion
  334. #region 生成指定长度的字符串
  335. /// <summary>
  336. /// 生成指定长度的字符串,即生成strLong个str字符串
  337. /// </summary>
  338. /// <param name="strLong">生成的长度</param>
  339. /// <param name="str">以str生成字符串</param>
  340. /// <returns></returns>
  341. public static string StringOfChar(int strLong, string str)
  342. {
  343. string ReturnStr = "";
  344. for (int i = 0; i < strLong; i++)
  345. {
  346. ReturnStr += str;
  347. }
  348. return ReturnStr;
  349. }
  350. #endregion
  351. #region 生成日期随机码
  352. /// <summary>
  353. /// 生成日期随机码
  354. /// </summary>
  355. /// <returns></returns>
  356. public static string GetRamCode()
  357. {
  358. #region
  359. return DateTime.Now.ToString("yyyyMMddHHmmssffff");
  360. #endregion
  361. }
  362. #endregion
  363. #region 生成随机字母或数字
  364. /// <summary>
  365. /// 生成随机数字
  366. /// </summary>
  367. /// <param name="length">生成长度</param>
  368. /// <returns></returns>
  369. public static string Number(int Length)
  370. {
  371. return Number(Length, false);
  372. }
  373. /// <summary>
  374. /// 生成随机数字
  375. /// </summary>
  376. /// <param name="Length">生成长度</param>
  377. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  378. /// <returns></returns>
  379. public static string Number(int Length, bool Sleep)
  380. {
  381. if (Sleep)
  382. System.Threading.Thread.Sleep(3);
  383. string result = "";
  384. System.Random random = new Random();
  385. for (int i = 0; i < Length; i++)
  386. {
  387. result += random.Next(10).ToString();
  388. }
  389. return result;
  390. }
  391. /// <summary>
  392. /// 生成随机字母字符串(数字字母混和)
  393. /// </summary>
  394. /// <param name="codeCount">待生成的位数</param>
  395. public static string GetCheckCode(int codeCount)
  396. {
  397. string str = string.Empty;
  398. int rep = 0;
  399. long num2 = DateTime.Now.Ticks + rep;
  400. rep++;
  401. Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
  402. for (int i = 0; i < codeCount; i++)
  403. {
  404. char ch;
  405. int num = random.Next();
  406. if ((num % 2) == 0)
  407. {
  408. ch = (char)(0x30 + ((ushort)(num % 10)));
  409. }
  410. else
  411. {
  412. ch = (char)(0x41 + ((ushort)(num % 0x1a)));
  413. }
  414. str = str + ch.ToString();
  415. }
  416. return str;
  417. }
  418. /// <summary>
  419. /// 根据日期和随机码生成订单号
  420. /// </summary>
  421. /// <returns></returns>
  422. public static string GetOrderNumber()
  423. {
  424. string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms
  425. return num + Number(2).ToString();
  426. }
  427. private static int Next(int numSeeds, int length)
  428. {
  429. byte[] buffer = new byte[length];
  430. System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
  431. Gen.GetBytes(buffer);
  432. uint randomResult = 0x0;//这里用uint作为生成的随机数
  433. for (int i = 0; i < length; i++)
  434. {
  435. randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
  436. }
  437. return (int)(randomResult % numSeeds);
  438. }
  439. #endregion
  440. #region 截取字符长度
  441. /// <summary>
  442. /// 截取字符长度
  443. /// </summary>
  444. /// <param name="inputString">字符</param>
  445. /// <param name="len">长度</param>
  446. /// <returns></returns>
  447. public static string CutString(string inputString, int len)
  448. {
  449. if (string.IsNullOrEmpty(inputString))
  450. return "";
  451. inputString = DropHTML(inputString);
  452. ASCIIEncoding ascii = new ASCIIEncoding();
  453. int tempLen = 0;
  454. string tempString = "";
  455. byte[] s = ascii.GetBytes(inputString);
  456. for (int i = 0; i < s.Length; i++)
  457. {
  458. if ((int)s[i] == 63)
  459. {
  460. tempLen += 2;
  461. }
  462. else
  463. {
  464. tempLen += 1;
  465. }
  466. try
  467. {
  468. tempString += inputString.Substring(i, 1);
  469. }
  470. catch
  471. {
  472. break;
  473. }
  474. if (tempLen > len)
  475. break;
  476. }
  477. //如果截过则加上半个省略号
  478. byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
  479. if (mybyte.Length > len)
  480. tempString += "…";
  481. return tempString;
  482. }
  483. #endregion
  484. #region 清除HTML标记
  485. public static string DropHTML(string Htmlstring)
  486. {
  487. if (string.IsNullOrEmpty(Htmlstring)) return "";
  488. //删除脚本
  489. Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
  490. //删除HTML
  491. Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
  492. Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
  493. Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
  494. Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
  495. Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
  496. Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
  497. Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
  498. Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
  499. Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
  500. Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
  501. Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
  502. Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
  503. Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
  504. Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
  505. Htmlstring.Replace("<", "");
  506. Htmlstring.Replace(">", "");
  507. Htmlstring.Replace("\r\n", "");
  508. Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
  509. return Htmlstring;
  510. }
  511. #endregion
  512. #region 清除HTML标记且返回相应的长度
  513. public static string DropHTML(string Htmlstring, int strLen)
  514. {
  515. return CutString(DropHTML(Htmlstring), strLen);
  516. }
  517. #endregion
  518. #region TXT代码转换成HTML格式
  519. /// <summary>
  520. /// 字符串字符处理
  521. /// </summary>
  522. /// <param name="chr">等待处理的字符串</param>
  523. /// <returns>处理后的字符串</returns>
  524. /// //把TXT代码转换成HTML格式
  525. public static String ToHtml(string Input)
  526. {
  527. StringBuilder sb = new StringBuilder(Input);
  528. sb.Replace("&", "&amp;");
  529. sb.Replace("<", "&lt;");
  530. sb.Replace(">", "&gt;");
  531. sb.Replace("\r\n", "<br />");
  532. sb.Replace("\n", "<br />");
  533. sb.Replace("\t", " ");
  534. //sb.Replace(" ", "&nbsp;");
  535. return sb.ToString();
  536. }
  537. #endregion
  538. #region HTML代码转换成TXT格式
  539. /// <summary>
  540. /// 字符串字符处理
  541. /// </summary>
  542. /// <param name="chr">等待处理的字符串</param>
  543. /// <returns>处理后的字符串</returns>
  544. /// //把HTML代码转换成TXT格式
  545. public static String ToTxt(String Input)
  546. {
  547. StringBuilder sb = new StringBuilder(Input);
  548. sb.Replace("&nbsp;", " ");
  549. sb.Replace("<br>", "\r\n");
  550. sb.Replace("<br>", "\n");
  551. sb.Replace("<br />", "\n");
  552. sb.Replace("<br />", "\r\n");
  553. sb.Replace("&lt;", "<");
  554. sb.Replace("&gt;", ">");
  555. sb.Replace("&amp;", "&");
  556. return sb.ToString();
  557. }
  558. #endregion
  559. #region 检测是否有Sql危险字符
  560. /// <summary>
  561. /// 检测是否有Sql危险字符
  562. /// </summary>
  563. /// <param name="str">要判断字符串</param>
  564. /// <returns>判断结果</returns>
  565. public static bool IsSafeSqlString(string str)
  566. {
  567. return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
  568. }
  569. /// <summary>
  570. /// 检查危险字符
  571. /// </summary>
  572. /// <param name="Input"></param>
  573. /// <returns></returns>
  574. public static string Filter(string sInput)
  575. {
  576. if (sInput == null || sInput == "")
  577. return null;
  578. string sInput1 = sInput.ToLower();
  579. string output = sInput;
  580. string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
  581. if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
  582. {
  583. throw new Exception("字符串中含有非法字符!");
  584. }
  585. else
  586. {
  587. output = output.Replace("'", "''");
  588. }
  589. return output;
  590. }
  591. /// <summary>
  592. /// 检查危险字符
  593. /// </summary>
  594. /// <param name="Input"></param>
  595. /// <returns></returns>
  596. public static string SqlFilter(string sInput)
  597. {
  598. if (sInput == null || sInput == "")
  599. return null;
  600. string sInput1 = sInput.ToLower();
  601. string output = sInput;
  602. //去掉星号*
  603. //string pattern = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
  604. string pattern = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
  605. if (Regex.Match(sInput1, @"\b(" + pattern + @")\b", RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
  606. {
  607. throw new Exception("字符串中含有非法字符!");
  608. }
  609. else
  610. {
  611. output = output.Replace("'", "''");
  612. }
  613. return output;
  614. }
  615. /// <summary>
  616. /// 检查过滤设定的危险字符
  617. /// </summary>
  618. /// <param name="InText">要过滤的字符串 </param>
  619. /// <returns>如果参数存在不安全字符,则返回true </returns>
  620. public static bool SqlFilter(string word, string InText)
  621. {
  622. if (InText == null)
  623. return false;
  624. foreach (string i in word.Split('|'))
  625. {
  626. if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
  627. {
  628. return true;
  629. }
  630. }
  631. return false;
  632. }
  633. #endregion
  634. #region 过滤特殊字符
  635. /// <summary>
  636. /// 过滤特殊字符
  637. /// </summary>
  638. /// <param name="Input"></param>
  639. /// <returns></returns>
  640. public static string Htmls(string Input)
  641. {
  642. if (Input != string.Empty && Input != null)
  643. {
  644. string ihtml = Input.ToLower();
  645. ihtml = ihtml.Replace("<script", "&lt;script");
  646. ihtml = ihtml.Replace("script>", "script&gt;");
  647. ihtml = ihtml.Replace("<%", "&lt;%");
  648. ihtml = ihtml.Replace("%>", "%&gt;");
  649. ihtml = ihtml.Replace("<$", "&lt;$");
  650. ihtml = ihtml.Replace("$>", "$&gt;");
  651. return ihtml;
  652. }
  653. else
  654. {
  655. return string.Empty;
  656. }
  657. }
  658. #endregion
  659. #region 检查是否为IP地址
  660. /// <summary>
  661. /// 是否为ip
  662. /// </summary>
  663. /// <param name="ip"></param>
  664. /// <returns></returns>
  665. public static bool IsIP(string ip)
  666. {
  667. return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
  668. }
  669. #endregion
  670. #region 获得配置文件节点XML文件的绝对路径
  671. public static string GetXmlMapPath(string xmlName)
  672. {
  673. return "";
  674. //return GetMapPath(ConfigurationManager.AppSettings[xmlName].ToString());
  675. }
  676. #endregion
  677. #region 获得当前绝对路径
  678. /// <summary>
  679. /// 获得当前绝对路径
  680. /// </summary>
  681. /// <param name="strPath">指定的路径</param>
  682. /// <returns>绝对路径</returns>
  683. public static string GetMapPath(string strPath)
  684. {
  685. if (strPath.ToLower().StartsWith("http://"))
  686. {
  687. return strPath;
  688. }
  689. if (HttpContext.Current != null)
  690. {
  691. return HttpContext.Current.Server.MapPath(strPath);
  692. }
  693. else //非web程序引用
  694. {
  695. strPath = strPath.Replace("/", "\\");
  696. if (strPath.StartsWith("\\"))
  697. {
  698. strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
  699. }
  700. return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
  701. }
  702. }
  703. //本地路径转换成URL相对路径
  704. public static string urlconvertor(string imagesurl1)
  705. {
  706. string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
  707. string imagesurl2 = imagesurl1.Replace(tmpRootDir, ""); //转换成相对路径
  708. imagesurl2 = imagesurl2.Replace(@"\", @"/");
  709. return imagesurl2;
  710. }
  711. //相对路径转换成服务器本地物理路径
  712. public static string urlconvertorlocal(string imagesurl1)
  713. {
  714. string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
  715. string imagesurl2 = tmpRootDir + imagesurl1.Replace(@"/", @"\"); //转换成绝对路径
  716. return imagesurl2;
  717. }
  718. #endregion
  719. #region 文件操作
  720. /// <summary>
  721. /// 删除单个文件
  722. /// </summary>
  723. /// <param name="_filepath">文件相对路径</param>
  724. public static bool DeleteFile(string _filepath)
  725. {
  726. if (string.IsNullOrEmpty(_filepath))
  727. {
  728. return false;
  729. }
  730. //string fullpath = GetMapPath(_filepath);
  731. string fullpath = urlconvertor(_filepath);
  732. if (File.Exists(fullpath))
  733. {
  734. File.Delete(fullpath);
  735. return true;
  736. }
  737. return false;
  738. }
  739. /// <summary>
  740. /// 删除上传的文件(及缩略图)
  741. /// </summary>
  742. /// <param name="_filepath"></param>
  743. public static void DeleteUpFile(string _filepath)
  744. {
  745. if (string.IsNullOrEmpty(_filepath))
  746. {
  747. return;
  748. }
  749. string fullpath = GetMapPath(_filepath); //原图
  750. if (File.Exists(fullpath))
  751. {
  752. File.Delete(fullpath);
  753. }
  754. if (_filepath.LastIndexOf("/") >= 0)
  755. {
  756. string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1);
  757. string fullTPATH = GetMapPath(thumbnailpath); //宿略图
  758. if (File.Exists(fullTPATH))
  759. {
  760. File.Delete(fullTPATH);
  761. }
  762. }
  763. }
  764. /// <summary>
  765. /// 返回文件大小KB
  766. /// </summary>
  767. /// <param name="_filepath">文件相对路径</param>
  768. /// <returns>int</returns>
  769. public static int GetFileSize(string _filepath)
  770. {
  771. if (string.IsNullOrEmpty(_filepath))
  772. {
  773. return 0;
  774. }
  775. string fullpath = GetMapPath(_filepath);
  776. if (File.Exists(fullpath))
  777. {
  778. FileInfo fileInfo = new FileInfo(fullpath);
  779. return ((int)fileInfo.Length) / 1024;
  780. }
  781. return 0;
  782. }
  783. /// <summary>
  784. /// 返回文件扩展名,不含“.”
  785. /// </summary>
  786. /// <param name="_filepath">文件全名称</param>
  787. /// <returns>string</returns>
  788. public static string GetFileExt(string _filepath)
  789. {
  790. if (string.IsNullOrEmpty(_filepath))
  791. {
  792. return "";
  793. }
  794. if (_filepath.LastIndexOf(".") > 0)
  795. {
  796. return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.”
  797. }
  798. return "";
  799. }
  800. /// <summary>
  801. /// 返回文件名,不含路径
  802. /// </summary>
  803. /// <param name="_filepath">文件相对路径</param>
  804. /// <returns>string</returns>
  805. public static string GetFileName(string _filepath)
  806. {
  807. return _filepath.Substring(_filepath.LastIndexOf(@"/") + 1);
  808. }
  809. /// <summary>
  810. /// 文件是否存在
  811. /// </summary>
  812. /// <param name="_filepath">文件相对路径</param>
  813. /// <returns>bool</returns>
  814. public static bool FileExists(string _filepath)
  815. {
  816. string fullpath = GetMapPath(_filepath);
  817. if (File.Exists(fullpath))
  818. {
  819. return true;
  820. }
  821. return false;
  822. }
  823. /// <summary>
  824. /// 获得远程字符串
  825. /// </summary>
  826. public static string GetDomainStr(string key, string uriPath)
  827. {
  828. string result = CacheHelper.Get(key) as string;
  829. if (result == null)
  830. {
  831. System.Net.WebClient client = new System.Net.WebClient();
  832. try
  833. {
  834. client.Encoding = System.Text.Encoding.UTF8;
  835. result = client.DownloadString(uriPath);
  836. }
  837. catch
  838. {
  839. result = "暂时无法连接!";
  840. }
  841. CacheHelper.Insert(key, result, 60);
  842. }
  843. return result;
  844. }
  845. #endregion
  846. #region 读取或写入cookie
  847. /// <summary>
  848. /// 写cookie值
  849. /// </summary>
  850. /// <param name="strName">名称</param>
  851. /// <param name="strValue">值</param>
  852. public static void WriteCookie(string strName, string strValue)
  853. {
  854. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  855. if (cookie == null)
  856. {
  857. cookie = new HttpCookie(strName);
  858. }
  859. cookie.Value = UrlEncode(strValue);
  860. HttpContext.Current.Response.AppendCookie(cookie);
  861. }
  862. /// <summary>
  863. /// 写cookie值
  864. /// </summary>
  865. /// <param name="strName">名称</param>
  866. /// <param name="strValue">值</param>
  867. public static void WriteCookie(string strName, string key, string strValue)
  868. {
  869. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  870. if (cookie == null)
  871. {
  872. cookie = new HttpCookie(strName);
  873. }
  874. cookie[key] = UrlEncode(strValue);
  875. HttpContext.Current.Response.AppendCookie(cookie);
  876. }
  877. /// <summary>
  878. /// 写cookie值
  879. /// </summary>
  880. /// <param name="strName">名称</param>
  881. /// <param name="strValue">值</param>
  882. public static void WriteCookie(string strName, string key, string strValue, int expires)
  883. {
  884. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  885. if (cookie == null)
  886. {
  887. cookie = new HttpCookie(strName);
  888. }
  889. cookie[key] = UrlEncode(strValue);
  890. cookie.Expires = DateTime.Now.AddMinutes(expires);
  891. HttpContext.Current.Response.AppendCookie(cookie);
  892. }
  893. /// <summary>
  894. /// 写cookie值
  895. /// </summary>
  896. /// <param name="strName">名称</param>
  897. /// <param name="strValue">值</param>
  898. /// <param name="strValue">过期时间(分钟)</param>
  899. public static void WriteCookie(string strName, string strValue, int expires)
  900. {
  901. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  902. if (cookie == null)
  903. {
  904. cookie = new HttpCookie(strName);
  905. }
  906. cookie.Value = UrlEncode(strValue);
  907. cookie.Expires = DateTime.Now.AddMinutes(expires);
  908. HttpContext.Current.Response.AppendCookie(cookie);
  909. }
  910. /// <summary>
  911. /// 读cookie值
  912. /// </summary>
  913. /// <param name="strName">名称</param>
  914. /// <returns>cookie值</returns>
  915. public static string GetCookie(string strName)
  916. {
  917. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  918. return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
  919. return "";
  920. }
  921. /// <summary>
  922. /// 读cookie值
  923. /// </summary>
  924. /// <param name="strName">名称</param>
  925. /// <returns>cookie值</returns>
  926. public static string GetCookie(string strName, string key)
  927. {
  928. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
  929. return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());
  930. return "";
  931. }
  932. #endregion
  933. #region 替换指定的字符串
  934. /// <summary>
  935. /// 替换指定的字符串
  936. /// </summary>
  937. /// <param name="originalStr">原字符串</param>
  938. /// <param name="oldStr">旧字符串</param>
  939. /// <param name="newStr">新字符串</param>
  940. /// <returns></returns>
  941. public static string ReplaceStr(string originalStr, string oldStr, string newStr)
  942. {
  943. if (string.IsNullOrEmpty(oldStr))
  944. {
  945. return "";
  946. }
  947. return originalStr.Replace(oldStr, newStr);
  948. }
  949. #endregion
  950. #region 显示分页
  951. /// <summary>
  952. /// 返回分页页码
  953. /// </summary>
  954. /// <param name="pageSize">页面大小</param>
  955. /// <param name="pageIndex">当前页</param>
  956. /// <param name="totalCount">总记录数</param>
  957. /// <param name="linkUrl">链接地址,__id__代表页码</param>
  958. /// <param name="centSize">中间页码数量</param>
  959. /// <returns></returns>
  960. public static string OutPageList(int pageSize, int pageIndex, int totalCount, string linkUrl, int centSize)
  961. {
  962. //计算页数
  963. if (totalCount < 1 || pageSize < 1)
  964. {
  965. return "";
  966. }
  967. int pageCount = totalCount / pageSize;
  968. if (pageCount < 1)
  969. {
  970. return "";
  971. }
  972. if (totalCount % pageSize > 0)
  973. {
  974. pageCount += 1;
  975. }
  976. if (pageCount <= 1)
  977. {
  978. return "";
  979. }
  980. StringBuilder pageStr = new StringBuilder();
  981. string pageId = "__id__";
  982. string firstBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex - 1).ToString()) + "\">«上一页</a>";
  983. string lastBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex + 1).ToString()) + "\">下一页»</a>";
  984. string firstStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, "1") + "\">1</a>";
  985. string lastStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, pageCount.ToString()) + "\">" + pageCount.ToString() + "</a>";
  986. if (pageIndex <= 1)
  987. {
  988. firstBtn = "<span class=\"disabled\">«上一页</span>";
  989. }
  990. if (pageIndex >= pageCount)
  991. {
  992. lastBtn = "<span class=\"disabled\">下一页»</span>";
  993. }
  994. if (pageIndex == 1)
  995. {
  996. firstStr = "<span class=\"current\">1</span>";
  997. }
  998. if (pageIndex == pageCount)
  999. {
  1000. lastStr = "<span class=\"current\">" + pageCount.ToString() + "</span>";
  1001. }
  1002. int firstNum = pageIndex - (centSize / 2); //中间开始的页码
  1003. if (pageIndex < centSize)
  1004. firstNum = 2;
  1005. int lastNum = pageIndex + centSize - ((centSize / 2) + 1); //中间结束的页码
  1006. if (lastNum >= pageCount)
  1007. lastNum = pageCount - 1;
  1008. pageStr.Append(firstBtn + firstStr);
  1009. if (pageIndex >= centSize)
  1010. {
  1011. pageStr.Append("<span>...</span>\n");
  1012. }
  1013. for (int i = firstNum; i <= lastNum; i++)
  1014. {
  1015. if (i == pageIndex)
  1016. {
  1017. pageStr.Append("<span class=\"current\">" + i + "</span>");
  1018. }
  1019. else
  1020. {
  1021. pageStr.Append("<a href=\"" + ReplaceStr(linkUrl, pageId, i.ToString()) + "\">" + i + "</a>");
  1022. }
  1023. }
  1024. if (pageCount - pageIndex > centSize - ((centSize / 2)))
  1025. {
  1026. pageStr.Append("<span>...</span>");
  1027. }
  1028. pageStr.Append(lastStr + lastBtn);
  1029. return pageStr.ToString();
  1030. }
  1031. #endregion
  1032. #region URL处理
  1033. /// <summary>
  1034. /// URL字符编码
  1035. /// </summary>
  1036. public static string UrlEncode(string str)
  1037. {
  1038. if (string.IsNullOrEmpty(str))
  1039. {
  1040. return "";
  1041. }
  1042. str = str.Replace("'", "");
  1043. return HttpContext.Current.Server.UrlEncode(str);
  1044. }
  1045. /// <summary>
  1046. /// URL字符解码
  1047. /// </summary>
  1048. public static string UrlDecode(string str)
  1049. {
  1050. if (string.IsNullOrEmpty(str))
  1051. {
  1052. return "";
  1053. }
  1054. return HttpContext.Current.Server.UrlDecode(str);
  1055. }
  1056. /// <summary>
  1057. /// 组合URL参数
  1058. /// </summary>
  1059. /// <param name="_url">页面地址</param>
  1060. /// <param name="_keys">参数名称</param>
  1061. /// <param name="_values">参数值</param>
  1062. /// <returns>String</returns>
  1063. public static string CombUrlTxt(string _url, string _keys, params string[] _values)
  1064. {
  1065. StringBuilder urlParams = new StringBuilder();
  1066. try
  1067. {
  1068. string[] keyArr = _keys.Split(new char[] { '&' });
  1069. for (int i = 0; i < keyArr.Length; i++)
  1070. {
  1071. if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0")
  1072. {
  1073. _values[i] = UrlEncode(_values[i]);
  1074. urlParams.Append(string.Format(keyArr[i], _values) + "&");
  1075. }
  1076. }
  1077. if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1)
  1078. urlParams.Insert(0, "?");
  1079. }
  1080. catch
  1081. {
  1082. return _url;
  1083. }
  1084. return _url + DelLastChar(urlParams.ToString(), "&");
  1085. }
  1086. #endregion
  1087. #region URL请求数据
  1088. /// <summary>
  1089. /// HTTP POST方式请求数据
  1090. /// </summary>
  1091. /// <param name="url">URL.</param>
  1092. /// <param name="param">POST的数据</param>
  1093. /// <returns></returns>
  1094. public static string HttpPost(string url, string param)
  1095. {
  1096. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  1097. request.Method = "POST";
  1098. request.ContentType = "application/x-www-form-urlencoded";
  1099. request.Accept = "*/*";
  1100. request.Timeout = 15000;
  1101. request.AllowAutoRedirect = false;
  1102. StreamWriter requestStream = null;
  1103. WebResponse response = null;
  1104. string responseStr = null;
  1105. try
  1106. {
  1107. requestStream = new StreamWriter(request.GetRequestStream());
  1108. requestStream.Write(param);
  1109. requestStream.Close();
  1110. response = request.GetResponse();
  1111. if (response != null)
  1112. {
  1113. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  1114. responseStr = reader.ReadToEnd();
  1115. reader.Close();
  1116. }
  1117. }
  1118. catch (Exception)
  1119. {
  1120. throw;
  1121. }
  1122. finally
  1123. {
  1124. request = null;
  1125. requestStream = null;
  1126. response = null;
  1127. }
  1128. return responseStr;
  1129. }
  1130. /// <summary>
  1131. /// HTTP GET方式请求数据.
  1132. /// </summary>
  1133. /// <param name="url">URL.</param>
  1134. /// <returns></returns>
  1135. public static string HttpGet(string url)
  1136. {
  1137. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  1138. request.Method = "GET";
  1139. //request.ContentType = "application/x-www-form-urlencoded";
  1140. request.Accept = "*/*";
  1141. request.Timeout = 15000;
  1142. request.AllowAutoRedirect = false;
  1143. WebResponse response = null;
  1144. string responseStr = null;
  1145. try
  1146. {
  1147. response = request.GetResponse();
  1148. if (response != null)
  1149. {
  1150. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  1151. responseStr = reader.ReadToEnd();
  1152. reader.Close();
  1153. }
  1154. }
  1155. catch (Exception)
  1156. {
  1157. throw;
  1158. }
  1159. finally
  1160. {
  1161. request = null;
  1162. response = null;
  1163. }
  1164. return responseStr;
  1165. }
  1166. /// <summary>
  1167. /// 执行URL获取页面内容
  1168. /// </summary>
  1169. public static string UrlExecute(string urlPath)
  1170. {
  1171. if (string.IsNullOrEmpty(urlPath))
  1172. {
  1173. return "error";
  1174. }
  1175. StringWriter sw = new StringWriter();
  1176. try
  1177. {
  1178. HttpContext.Current.Server.Execute(urlPath, sw);
  1179. return sw.ToString();
  1180. }
  1181. catch (Exception)
  1182. {
  1183. return "error";
  1184. }
  1185. finally
  1186. {
  1187. sw.Close();
  1188. sw.Dispose();
  1189. }
  1190. }
  1191. #endregion
  1192. public static string ToEnumDescriptionString(this int value, Type enumType)
  1193. {
  1194. NameValueCollection nvc = GetNVCFromEnumValue(enumType);
  1195. return nvc[value.ToString()];
  1196. }
  1197. public static NameValueCollection GetNVCFromEnumValue(Type enumType)
  1198. {
  1199. NameValueCollection nvc = new NameValueCollection();
  1200. Type typeDescription = typeof(DescriptionAttribute);
  1201. System.Reflection.FieldInfo[] fields = enumType.GetFields();
  1202. string strText = string.Empty;
  1203. string strValue = string.Empty;
  1204. foreach (FieldInfo field in fields)
  1205. {
  1206. if (field.FieldType.IsEnum)
  1207. {
  1208. strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
  1209. object[] arr = field.GetCustomAttributes(typeDescription, true);
  1210. if (arr.Length > 0)
  1211. {
  1212. DescriptionAttribute aa = (DescriptionAttribute)arr[0];
  1213. strText = aa.Description;
  1214. }
  1215. else
  1216. {
  1217. strText = "";
  1218. }
  1219. nvc.Add(strValue, strText);
  1220. }
  1221. }
  1222. return nvc;
  1223. }
  1224. }
  1225. }