Brak opisu

Utils.cs 42KB

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