郑州颐和随访系统

Utils.cs 43KB

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