Ei kuvausta

Utils.cs 44KB

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