市长热线演示版

Utils.cs 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. using System.IO;
  6. using System.Net;
  7. using System.Configuration;
  8. using System.Web;
  9. namespace HySoft.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");//yyyyMMddHHmmssms
  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 GetMapPath(ConfigurationManager.AppSettings[xmlName].ToString());
  647. }
  648. #endregion
  649. #region 获得当前绝对路径
  650. /// <summary>
  651. /// 获得当前绝对路径
  652. /// </summary>
  653. /// <param name="strPath">指定的路径</param>
  654. /// <returns>绝对路径</returns>
  655. public static string GetMapPath(string strPath)
  656. {
  657. if (strPath.ToLower().StartsWith("http://"))
  658. {
  659. return strPath;
  660. }
  661. if (HttpContext.Current != null)
  662. {
  663. return HttpContext.Current.Server.MapPath(strPath);
  664. }
  665. else //非web程序引用
  666. {
  667. strPath = strPath.Replace("/", "\\");
  668. if (strPath.StartsWith("\\"))
  669. {
  670. strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
  671. }
  672. return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
  673. }
  674. }
  675. #endregion
  676. #region 文件操作
  677. /// <summary>
  678. /// 删除单个文件
  679. /// </summary>
  680. /// <param name="_filepath">文件相对路径</param>
  681. public static bool DeleteFile(string _filepath)
  682. {
  683. if (string.IsNullOrEmpty(_filepath))
  684. {
  685. return false;
  686. }
  687. string fullpath = GetMapPath(_filepath);
  688. if (File.Exists(fullpath))
  689. {
  690. File.Delete(fullpath);
  691. return true;
  692. }
  693. return false;
  694. }
  695. /// <summary>
  696. /// 删除上传的文件(及缩略图)
  697. /// </summary>
  698. /// <param name="_filepath"></param>
  699. public static void DeleteUpFile(string _filepath)
  700. {
  701. if (string.IsNullOrEmpty(_filepath))
  702. {
  703. return;
  704. }
  705. string fullpath = GetMapPath(_filepath); //原图
  706. if (File.Exists(fullpath))
  707. {
  708. File.Delete(fullpath);
  709. }
  710. if (_filepath.LastIndexOf("/") >= 0)
  711. {
  712. string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1);
  713. string fullTPATH = GetMapPath(thumbnailpath); //宿略图
  714. if (File.Exists(fullTPATH))
  715. {
  716. File.Delete(fullTPATH);
  717. }
  718. }
  719. }
  720. /// <summary>
  721. /// 返回文件大小KB
  722. /// </summary>
  723. /// <param name="_filepath">文件相对路径</param>
  724. /// <returns>int</returns>
  725. public static int GetFileSize(string _filepath)
  726. {
  727. if (string.IsNullOrEmpty(_filepath))
  728. {
  729. return 0;
  730. }
  731. string fullpath = GetMapPath(_filepath);
  732. if (File.Exists(fullpath))
  733. {
  734. FileInfo fileInfo = new FileInfo(fullpath);
  735. return ((int)fileInfo.Length) / 1024;
  736. }
  737. return 0;
  738. }
  739. /// <summary>
  740. /// 返回文件扩展名,不含“.”
  741. /// </summary>
  742. /// <param name="_filepath">文件全名称</param>
  743. /// <returns>string</returns>
  744. public static string GetFileExt(string _filepath)
  745. {
  746. if (string.IsNullOrEmpty(_filepath))
  747. {
  748. return "";
  749. }
  750. if (_filepath.LastIndexOf(".") > 0)
  751. {
  752. return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.”
  753. }
  754. return "";
  755. }
  756. /// <summary>
  757. /// 返回文件名,不含路径
  758. /// </summary>
  759. /// <param name="_filepath">文件相对路径</param>
  760. /// <returns>string</returns>
  761. public static string GetFileName(string _filepath)
  762. {
  763. return _filepath.Substring(_filepath.LastIndexOf(@"/") + 1);
  764. }
  765. /// <summary>
  766. /// 文件是否存在
  767. /// </summary>
  768. /// <param name="_filepath">文件相对路径</param>
  769. /// <returns>bool</returns>
  770. public static bool FileExists(string _filepath)
  771. {
  772. string fullpath = GetMapPath(_filepath);
  773. if (File.Exists(fullpath))
  774. {
  775. return true;
  776. }
  777. return false;
  778. }
  779. /// <summary>
  780. /// 获得远程字符串
  781. /// </summary>
  782. public static string GetDomainStr(string key, string uriPath)
  783. {
  784. string result = CacheHelper.Get(key) as string;
  785. if (result == null)
  786. {
  787. System.Net.WebClient client = new System.Net.WebClient();
  788. try
  789. {
  790. client.Encoding = System.Text.Encoding.UTF8;
  791. result = client.DownloadString(uriPath);
  792. }
  793. catch
  794. {
  795. result = "暂时无法连接!";
  796. }
  797. CacheHelper.Insert(key, result, 60);
  798. }
  799. return result;
  800. }
  801. #endregion
  802. #region 读取或写入cookie
  803. /// <summary>
  804. /// 写cookie值
  805. /// </summary>
  806. /// <param name="strName">名称</param>
  807. /// <param name="strValue">值</param>
  808. public static void WriteCookie(string strName, string strValue)
  809. {
  810. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  811. if (cookie == null)
  812. {
  813. cookie = new HttpCookie(strName);
  814. }
  815. cookie.Value = UrlEncode(strValue);
  816. HttpContext.Current.Response.AppendCookie(cookie);
  817. }
  818. /// <summary>
  819. /// 写cookie值
  820. /// </summary>
  821. /// <param name="strName">名称</param>
  822. /// <param name="strValue">值</param>
  823. public static void WriteCookie(string strName, string key, string strValue)
  824. {
  825. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  826. if (cookie == null)
  827. {
  828. cookie = new HttpCookie(strName);
  829. }
  830. cookie[key] = UrlEncode(strValue);
  831. HttpContext.Current.Response.AppendCookie(cookie);
  832. }
  833. /// <summary>
  834. /// 写cookie值
  835. /// </summary>
  836. /// <param name="strName">名称</param>
  837. /// <param name="strValue">值</param>
  838. public static void WriteCookie(string strName, string key, string strValue, int expires)
  839. {
  840. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  841. if (cookie == null)
  842. {
  843. cookie = new HttpCookie(strName);
  844. }
  845. cookie[key] = UrlEncode(strValue);
  846. cookie.Expires = DateTime.Now.AddMinutes(expires);
  847. HttpContext.Current.Response.AppendCookie(cookie);
  848. }
  849. /// <summary>
  850. /// 写cookie值
  851. /// </summary>
  852. /// <param name="strName">名称</param>
  853. /// <param name="strValue">值</param>
  854. /// <param name="strValue">过期时间(分钟)</param>
  855. public static void WriteCookie(string strName, string strValue, int expires)
  856. {
  857. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  858. if (cookie == null)
  859. {
  860. cookie = new HttpCookie(strName);
  861. }
  862. cookie.Value = UrlEncode(strValue);
  863. cookie.Expires = DateTime.Now.AddMinutes(expires);
  864. HttpContext.Current.Response.AppendCookie(cookie);
  865. }
  866. /// <summary>
  867. /// 读cookie值
  868. /// </summary>
  869. /// <param name="strName">名称</param>
  870. /// <returns>cookie值</returns>
  871. public static string GetCookie(string strName)
  872. {
  873. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  874. return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
  875. return "";
  876. }
  877. /// <summary>
  878. /// 读cookie值
  879. /// </summary>
  880. /// <param name="strName">名称</param>
  881. /// <returns>cookie值</returns>
  882. public static string GetCookie(string strName, string key)
  883. {
  884. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
  885. return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());
  886. return "";
  887. }
  888. #endregion
  889. #region 替换指定的字符串
  890. /// <summary>
  891. /// 替换指定的字符串
  892. /// </summary>
  893. /// <param name="originalStr">原字符串</param>
  894. /// <param name="oldStr">旧字符串</param>
  895. /// <param name="newStr">新字符串</param>
  896. /// <returns></returns>
  897. public static string ReplaceStr(string originalStr, string oldStr, string newStr)
  898. {
  899. if (string.IsNullOrEmpty(oldStr))
  900. {
  901. return "";
  902. }
  903. return originalStr.Replace(oldStr, newStr);
  904. }
  905. #endregion
  906. #region 显示分页
  907. /// <summary>
  908. /// 返回分页页码
  909. /// </summary>
  910. /// <param name="pageSize">页面大小</param>
  911. /// <param name="pageIndex">当前页</param>
  912. /// <param name="totalCount">总记录数</param>
  913. /// <param name="linkUrl">链接地址,__id__代表页码</param>
  914. /// <param name="centSize">中间页码数量</param>
  915. /// <returns></returns>
  916. public static string OutPageList(int pageSize, int pageIndex, int totalCount, string linkUrl, int centSize)
  917. {
  918. //计算页数
  919. if (totalCount < 1 || pageSize < 1)
  920. {
  921. return "";
  922. }
  923. int pageCount = totalCount / pageSize;
  924. if (pageCount < 1)
  925. {
  926. return "";
  927. }
  928. if (totalCount % pageSize > 0)
  929. {
  930. pageCount += 1;
  931. }
  932. if (pageCount <= 1)
  933. {
  934. return "";
  935. }
  936. StringBuilder pageStr = new StringBuilder();
  937. string pageId = "__id__";
  938. string firstBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex - 1).ToString()) + "\">«上一页</a>";
  939. string lastBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex + 1).ToString()) + "\">下一页»</a>";
  940. string firstStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, "1") + "\">1</a>";
  941. string lastStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, pageCount.ToString()) + "\">" + pageCount.ToString() + "</a>";
  942. if (pageIndex <= 1)
  943. {
  944. firstBtn = "<span class=\"disabled\">«上一页</span>";
  945. }
  946. if (pageIndex >= pageCount)
  947. {
  948. lastBtn = "<span class=\"disabled\">下一页»</span>";
  949. }
  950. if (pageIndex == 1)
  951. {
  952. firstStr = "<span class=\"current\">1</span>";
  953. }
  954. if (pageIndex == pageCount)
  955. {
  956. lastStr = "<span class=\"current\">" + pageCount.ToString() + "</span>";
  957. }
  958. int firstNum = pageIndex - (centSize / 2); //中间开始的页码
  959. if (pageIndex < centSize)
  960. firstNum = 2;
  961. int lastNum = pageIndex + centSize - ((centSize / 2) + 1); //中间结束的页码
  962. if (lastNum >= pageCount)
  963. lastNum = pageCount - 1;
  964. pageStr.Append(firstBtn + firstStr);
  965. if (pageIndex >= centSize)
  966. {
  967. pageStr.Append("<span>...</span>\n");
  968. }
  969. for (int i = firstNum; i <= lastNum; i++)
  970. {
  971. if (i == pageIndex)
  972. {
  973. pageStr.Append("<span class=\"current\">" + i + "</span>");
  974. }
  975. else
  976. {
  977. pageStr.Append("<a href=\"" + ReplaceStr(linkUrl, pageId, i.ToString()) + "\">" + i + "</a>");
  978. }
  979. }
  980. if (pageCount - pageIndex > centSize - ((centSize / 2)))
  981. {
  982. pageStr.Append("<span>...</span>");
  983. }
  984. pageStr.Append(lastStr + lastBtn);
  985. return pageStr.ToString();
  986. }
  987. #endregion
  988. #region URL处理
  989. /// <summary>
  990. /// URL字符编码
  991. /// </summary>
  992. public static string UrlEncode(string str)
  993. {
  994. if (string.IsNullOrEmpty(str))
  995. {
  996. return "";
  997. }
  998. str = str.Replace("'", "");
  999. return HttpContext.Current.Server.UrlEncode(str);
  1000. }
  1001. /// <summary>
  1002. /// URL字符解码
  1003. /// </summary>
  1004. public static string UrlDecode(string str)
  1005. {
  1006. if (string.IsNullOrEmpty(str))
  1007. {
  1008. return "";
  1009. }
  1010. return HttpContext.Current.Server.UrlDecode(str);
  1011. }
  1012. /// <summary>
  1013. /// 组合URL参数
  1014. /// </summary>
  1015. /// <param name="_url">页面地址</param>
  1016. /// <param name="_keys">参数名称</param>
  1017. /// <param name="_values">参数值</param>
  1018. /// <returns>String</returns>
  1019. public static string CombUrlTxt(string _url, string _keys, params string[] _values)
  1020. {
  1021. StringBuilder urlParams = new StringBuilder();
  1022. try
  1023. {
  1024. string[] keyArr = _keys.Split(new char[] { '&' });
  1025. for (int i = 0; i < keyArr.Length; i++)
  1026. {
  1027. if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0")
  1028. {
  1029. _values[i] = UrlEncode(_values[i]);
  1030. urlParams.Append(string.Format(keyArr[i], _values) + "&");
  1031. }
  1032. }
  1033. if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1)
  1034. urlParams.Insert(0, "?");
  1035. }
  1036. catch
  1037. {
  1038. return _url;
  1039. }
  1040. return _url + DelLastChar(urlParams.ToString(), "&");
  1041. }
  1042. #endregion
  1043. #region URL请求数据
  1044. /// <summary>
  1045. /// HTTP POST方式请求数据
  1046. /// </summary>
  1047. /// <param name="url">URL.</param>
  1048. /// <param name="param">POST的数据</param>
  1049. /// <returns></returns>
  1050. public static string HttpPost(string url, string param)
  1051. {
  1052. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  1053. request.Method = "POST";
  1054. request.ContentType = "application/x-www-form-urlencoded";
  1055. request.Accept = "*/*";
  1056. request.Timeout = 15000;
  1057. request.AllowAutoRedirect = false;
  1058. StreamWriter requestStream = null;
  1059. WebResponse response = null;
  1060. string responseStr = null;
  1061. try
  1062. {
  1063. requestStream = new StreamWriter(request.GetRequestStream());
  1064. requestStream.Write(param);
  1065. requestStream.Close();
  1066. response = request.GetResponse();
  1067. if (response != null)
  1068. {
  1069. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  1070. responseStr = reader.ReadToEnd();
  1071. reader.Close();
  1072. }
  1073. }
  1074. catch (Exception)
  1075. {
  1076. throw;
  1077. }
  1078. finally
  1079. {
  1080. request = null;
  1081. requestStream = null;
  1082. response = null;
  1083. }
  1084. return responseStr;
  1085. }
  1086. /// <summary>
  1087. /// HTTP GET方式请求数据.
  1088. /// </summary>
  1089. /// <param name="url">URL.</param>
  1090. /// <returns></returns>
  1091. public static string HttpGet(string url)
  1092. {
  1093. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  1094. request.Method = "GET";
  1095. //request.ContentType = "application/x-www-form-urlencoded";
  1096. request.Accept = "*/*";
  1097. request.Timeout = 15000;
  1098. request.AllowAutoRedirect = false;
  1099. WebResponse response = null;
  1100. string responseStr = null;
  1101. try
  1102. {
  1103. response = request.GetResponse();
  1104. if (response != null)
  1105. {
  1106. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  1107. responseStr = reader.ReadToEnd();
  1108. reader.Close();
  1109. }
  1110. }
  1111. catch (Exception)
  1112. {
  1113. throw;
  1114. }
  1115. finally
  1116. {
  1117. request = null;
  1118. response = null;
  1119. }
  1120. return responseStr;
  1121. }
  1122. /// <summary>
  1123. /// 执行URL获取页面内容
  1124. /// </summary>
  1125. public static string UrlExecute(string urlPath)
  1126. {
  1127. if (string.IsNullOrEmpty(urlPath))
  1128. {
  1129. return "error";
  1130. }
  1131. StringWriter sw = new StringWriter();
  1132. try
  1133. {
  1134. HttpContext.Current.Server.Execute(urlPath, sw);
  1135. return sw.ToString();
  1136. }
  1137. catch (Exception)
  1138. {
  1139. return "error";
  1140. }
  1141. finally
  1142. {
  1143. sw.Close();
  1144. sw.Dispose();
  1145. }
  1146. }
  1147. #endregion
  1148. }
  1149. }