新野县12345_后端

Utils.cs 44KB

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