Utils.cs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web;
  4. using System.Data;
  5. using System.Text.RegularExpressions;
  6. using System.Diagnostics;
  7. using System.Reflection;
  8. using System.Text;
  9. using System.IO;
  10. using System.Runtime.InteropServices;
  11. using System.Collections;
  12. using System.Configuration;
  13. using System.Security.Cryptography;
  14. using System.Drawing;
  15. using System.Web.Security;
  16. using System.Runtime.Serialization.Formatters.Binary;
  17. namespace ETD.Frame
  18. {
  19. /// <summary>
  20. ///处理字符串类
  21. /// </summary>
  22. public class Utils
  23. {
  24. private static Regex RegexBr = new Regex(@"(\r\n)", RegexOptions.IgnoreCase);
  25. public static Regex RegexFont = new Regex(@"<font color=" + "\".*?\"" + @">([\s\S]+?)</font>", Utils.GetRegexCompiledOptions());
  26. private static FileVersionInfo AssemblyFileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
  27. private static string TemplateCookieName = string.Format("dnttemplateid_{0}_{1}_{2}", AssemblyFileVersion.FileMajorPart, AssemblyFileVersion.FileMinorPart, AssemblyFileVersion.FileBuildPart);
  28. /// <summary>
  29. /// 得到正则编译参数设置
  30. /// </summary>
  31. /// <returns></returns>
  32. public static RegexOptions GetRegexCompiledOptions()
  33. {
  34. #if NET1
  35. return RegexOptions.Compiled;
  36. #else
  37. return RegexOptions.None;
  38. #endif
  39. }
  40. /// <summary>
  41. /// 返回字符串真实长度, 1个汉字长度为2
  42. /// </summary>
  43. /// <returns></returns>
  44. public static int GetStringLength(string str)
  45. {
  46. return Encoding.Default.GetBytes(str).Length;
  47. }
  48. public static bool IsCompriseStr(string str, string stringarray, string strsplit)
  49. {
  50. if (stringarray == "" || stringarray == null)
  51. {
  52. return false;
  53. }
  54. str = str.ToLower();
  55. string[] stringArray = Utils.SplitString(stringarray.ToLower(), strsplit);
  56. for (int i = 0; i < stringArray.Length; i++)
  57. {
  58. //string t1 = str;
  59. //string t2 = stringArray[i];
  60. if (str.IndexOf(stringArray[i]) > -1)
  61. {
  62. return true;
  63. }
  64. }
  65. return false;
  66. }
  67. /// <summary>
  68. /// 判断指定字符串在指定字符串数组中的位置
  69. /// </summary>
  70. /// <param name="strSearch">字符串</param>
  71. /// <param name="stringArray">字符串数组</param>
  72. /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
  73. /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
  74. public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive)
  75. {
  76. for (int i = 0; i < stringArray.Length; i++)
  77. {
  78. if (caseInsensetive)
  79. {
  80. if (strSearch.ToLower() == stringArray[i].ToLower())
  81. {
  82. return i;
  83. }
  84. }
  85. else
  86. {
  87. if (strSearch == stringArray[i])
  88. {
  89. return i;
  90. }
  91. }
  92. }
  93. return -1;
  94. }
  95. /// <summary>
  96. /// 判断指定字符串在指定字符串数组中的位置
  97. /// </summary>
  98. /// <param name="strSearch">字符串</param>
  99. /// <param name="stringArray">字符串数组</param>
  100. /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
  101. public static int GetInArrayID(string strSearch, string[] stringArray)
  102. {
  103. return GetInArrayID(strSearch, stringArray, true);
  104. }
  105. /// <summary>
  106. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  107. /// </summary>
  108. /// <param name="strSearch">字符串</param>
  109. /// <param name="stringArray">字符串数组</param>
  110. /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
  111. /// <returns>判断结果</returns>
  112. public static bool InArray(string strSearch, string[] stringArray, bool caseInsensetive)
  113. {
  114. return GetInArrayID(strSearch, stringArray, caseInsensetive) >= 0;
  115. }
  116. /// <summary>
  117. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  118. /// </summary>
  119. /// <param name="str">字符串</param>
  120. /// <param name="stringarray">字符串数组</param>
  121. /// <returns>判断结果</returns>
  122. public static bool InArray(string str, string[] stringarray)
  123. {
  124. return InArray(str, stringarray, false);
  125. }
  126. /// <summary>
  127. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  128. /// </summary>
  129. /// <param name="str">字符串</param>
  130. /// <param name="stringarray">内部以逗号分割单词的字符串</param>
  131. /// <returns>判断结果</returns>
  132. public static bool InArray(string str, string stringarray)
  133. {
  134. return InArray(str, SplitString(stringarray, ","), false);
  135. }
  136. /// <summary>
  137. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  138. /// </summary>
  139. /// <param name="str">字符串</param>
  140. /// <param name="stringarray">内部以逗号分割单词的字符串</param>
  141. /// <param name="strsplit">分割字符串</param>
  142. /// <returns>判断结果</returns>
  143. public static bool InArray(string str, string stringarray, string strsplit)
  144. {
  145. return InArray(str, SplitString(stringarray, strsplit), false);
  146. }
  147. /// <summary>
  148. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  149. /// </summary>
  150. /// <param name="str">字符串</param>
  151. /// <param name="stringarray">内部以逗号分割单词的字符串</param>
  152. /// <param name="strsplit">分割字符串</param>
  153. /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
  154. /// <returns>判断结果</returns>
  155. public static bool InArray(string str, string stringarray, string strsplit, bool caseInsensetive)
  156. {
  157. return InArray(str, SplitString(stringarray, strsplit), caseInsensetive);
  158. }
  159. /// <summary>
  160. /// 删除字符串尾部的回车/换行/空格
  161. /// </summary>
  162. /// <param name="str"></param>
  163. /// <returns></returns>
  164. public static string RTrim(string str)
  165. {
  166. for (int i = str.Length; i >= 0; i--)
  167. {
  168. if (str[i].Equals(" ") || str[i].Equals("\r") || str[i].Equals("\n"))
  169. {
  170. str.Remove(i, 1);
  171. }
  172. }
  173. return str;
  174. }
  175. /// <summary>
  176. /// 清除给定字符串中的回车及换行符
  177. /// </summary>
  178. /// <param name="str">要清除的字符串</param>
  179. /// <returns>清除后返回的字符串</returns>
  180. public static string ClearBR(string str)
  181. {
  182. //Regex r = null;
  183. Match m = null;
  184. //r = new Regex(@"(\r\n)",RegexOptions.IgnoreCase);
  185. for (m = RegexBr.Match(str); m.Success; m = m.NextMatch())
  186. {
  187. str = str.Replace(m.Groups[0].ToString(), "");
  188. }
  189. return str;
  190. }
  191. /// <summary>
  192. /// 从字符串的指定位置截取指定长度的子字符串并添加说明字符串
  193. /// </summary>
  194. /// <param name="str">原字符串</param>
  195. /// <param name="startIndex">子字符串的起始位置</param>
  196. /// <param name="length">子字符串的长度</param>
  197. /// <param name="appendStr">添加被截字符串后的说明字符串</param>
  198. /// <returns>子字符串</returns>
  199. public static string CutString(string str, int startIndex, int length, string appendStr)
  200. {
  201. return str.Length >= length ? CutString(str, startIndex, length) + appendStr : str;
  202. }
  203. /// <summary>
  204. /// 从字符串的指定位置截取指定长度的子字符串
  205. /// </summary>
  206. /// <param name="str">原字符串</param>
  207. /// <param name="startIndex">子字符串的起始位置</param>
  208. /// <param name="length">子字符串的长度</param>
  209. /// <returns>子字符串</returns>
  210. public static string CutString(string str, int startIndex, int length)
  211. {
  212. if (startIndex >= 0)
  213. {
  214. if (length < 0)
  215. {
  216. length = length * -1;
  217. if (startIndex - length < 0)
  218. {
  219. length = startIndex;
  220. startIndex = 0;
  221. }
  222. else
  223. {
  224. startIndex = startIndex - length;
  225. }
  226. }
  227. if (startIndex > str.Length)
  228. {
  229. return "";
  230. }
  231. }
  232. else
  233. {
  234. if (length < 0)
  235. {
  236. return "";
  237. }
  238. else
  239. {
  240. if (length + startIndex > 0)
  241. {
  242. length = length + startIndex;
  243. startIndex = 0;
  244. }
  245. else
  246. {
  247. return "";
  248. }
  249. }
  250. }
  251. if (str.Length - startIndex < length)
  252. {
  253. length = str.Length - startIndex;
  254. }
  255. return str.Substring(startIndex, length);
  256. }
  257. public enum type
  258. {
  259. /// <summary>
  260. /// 标识对字符解码
  261. /// </summary>
  262. unescape,
  263. /// <summary>
  264. /// 标识对字符加码
  265. /// </summary>
  266. escape
  267. }
  268. /// <summary>
  269. /// 剩余时间的计算 使用方式 LTime(Eval("StartTime").ToString(), Eval("ProjectIndate").ToString()
  270. /// </summary>
  271. /// <param name="StartTime">开始时间</param>
  272. /// <param name="Numer">延期时间</param>
  273. /// <returns>剩余时间</returns>
  274. public static string LTime(string StartTime, string Numer)
  275. {
  276. DateTime dTime = DateTime.Parse(StartTime);
  277. int INum = Int32.Parse(Numer);
  278. DateTime eTime = dTime.AddDays(INum);
  279. if (eTime < DateTime.Now)
  280. {
  281. return "<font color='red'>已过期</font>";
  282. }
  283. else
  284. {
  285. TimeSpan ss = new TimeSpan();
  286. ss = eTime.Subtract(DateTime.Now);
  287. return ss.Days + "天," + ss.Hours + "时";
  288. }
  289. }
  290. public static string CutContent(string content, int length)
  291. {
  292. if (content.Length > length)
  293. {
  294. content = content.Substring(0, length) + "...";
  295. }
  296. return content;
  297. }
  298. public static string GetParam(string paramname)
  299. {
  300. string myid = "";
  301. string urlString = HttpContext.Current.Request.UrlReferrer.AbsoluteUri;
  302. string[] urlPas = urlString.Split(new string[] { "?", "=", "&" }, StringSplitOptions.RemoveEmptyEntries);
  303. for (int i = 0, count = urlPas.Length; i < count; i++)
  304. {
  305. if (urlPas[i].ToLower().Trim() == paramname.ToLower().Trim())
  306. {
  307. if (i + 1 < count)
  308. {
  309. myid = urlPas[i + 1];
  310. }
  311. else
  312. {
  313. myid = string.Empty;
  314. }
  315. break;
  316. }
  317. }
  318. return myid;
  319. }
  320. /// <summary>
  321. /// 处理数据字段长度
  322. /// </summary>
  323. /// <param name="url"></param>
  324. /// <returns></returns>
  325. public static string SubStr(string str, int length)
  326. {
  327. if (str.Length > length)
  328. {
  329. return str.Substring(0, length) + "...";
  330. }
  331. else
  332. {
  333. return str;
  334. }
  335. }
  336. /// <summary>
  337. /// 处理数据字段长度
  338. /// </summary>
  339. /// <param name="url"></param>
  340. /// <returns></returns>
  341. public static string SubShopnameStr(string str, int length)
  342. {
  343. if (str.Length > length)
  344. {
  345. return str.Substring(0, length);
  346. }
  347. else
  348. {
  349. return str;
  350. }
  351. }
  352. /// <summary>
  353. /// 从字符串的指定位置开始截取到字符串结尾的了符串
  354. /// </summary>
  355. /// <param name="str">原字符串</param>
  356. /// <param name="startIndex">子字符串的起始位置</param>
  357. /// <returns>子字符串</returns>
  358. public static string CutString(string str, int startIndex)
  359. {
  360. return CutString(str, startIndex, str.Length);
  361. }
  362. /// <summary>
  363. /// 获得当前绝对路径
  364. /// </summary>
  365. /// <param name="strPath">指定的路径</param>
  366. /// <returns>绝对路径</returns>
  367. public static string GetMapPath(string strPath)
  368. {
  369. if (HttpContext.Current != null)
  370. {
  371. return HttpContext.Current.Server.MapPath(strPath);
  372. }
  373. else //非web程序引用
  374. {
  375. return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
  376. }
  377. }
  378. /// <summary>
  379. /// 返回文件是否存在
  380. /// </summary>
  381. /// <param name="filename">文件名</param>
  382. /// <returns>是否存在</returns>
  383. public static bool FileExists(string filename)
  384. {
  385. return System.IO.File.Exists(filename);
  386. }
  387. /// <summary>
  388. /// 判断文件名是否为浏览器可以直接显示的图片文件名
  389. /// </summary>
  390. /// <param name="filename">文件名</param>
  391. /// <returns>是否可以直接显示</returns>
  392. public static bool IsImgFilename(string filename)
  393. {
  394. filename = filename.Trim();
  395. if (filename.EndsWith(".") || filename.IndexOf(".") == -1)
  396. {
  397. return false;
  398. }
  399. string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
  400. return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif");
  401. }
  402. /// <summary>
  403. /// int型转换为string型
  404. /// </summary>
  405. /// <returns>转换后的string类型结果</returns>
  406. public static string IntToStr(int intValue)
  407. {
  408. //
  409. return Convert.ToString(intValue);
  410. }
  411. /// <summary>
  412. /// MD5函数
  413. /// </summary>
  414. /// <param name="str">原始字符串</param>
  415. /// <returns>MD5结果</returns>
  416. public static string MD5(string str)
  417. {
  418. //byte[] b = Encoding.Default.GetBytes(str);
  419. //b = new MD5CryptoServiceProvider().ComputeHash(b);
  420. //string ret = "";
  421. //for (int i = 0; i < b.Length; i++)
  422. // ret += b[i].ToString("x").PadLeft(2, '0');
  423. return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
  424. }
  425. /// <summary>
  426. /// SHA256函数
  427. /// </summary>
  428. /// /// <param name="str">原始字符串</param>
  429. /// <returns>SHA256结果</returns>
  430. public static string SHA256(string str)
  431. {
  432. byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
  433. SHA256Managed Sha256 = new SHA256Managed();
  434. byte[] Result = Sha256.ComputeHash(SHA256Data);
  435. return Convert.ToBase64String(Result); //返回长度为44字节的字符串
  436. }
  437. /// <summary>
  438. /// 字符串如果操过指定长度则将超出的部分用指定字符串代替
  439. /// </summary>
  440. /// <param name="p_SrcString">要检查的字符串</param>
  441. /// <param name="p_Length">指定长度</param>
  442. /// <param name="p_TailString">用于替换的字符串</param>
  443. /// <returns>截取后的字符串</returns>
  444. public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
  445. {
  446. return GetSubString(p_SrcString, 0, p_Length, p_TailString);
  447. }
  448. /// <summary>
  449. /// 取指定长度的字符串
  450. /// </summary>
  451. /// <param name="p_SrcString">要检查的字符串</param>
  452. /// <param name="p_StartIndex">起始位置</param>
  453. /// <param name="p_Length">指定长度</param>
  454. /// <param name="p_TailString">用于替换的字符串</param>
  455. /// <returns>截取后的字符串</returns>
  456. public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
  457. {
  458. string myResult = p_SrcString;
  459. //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
  460. if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") ||
  461. System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+"))
  462. {
  463. //当截取的起始位置超出字段串长度时
  464. if (p_StartIndex >= p_SrcString.Length)
  465. {
  466. return "";
  467. }
  468. else
  469. {
  470. return p_SrcString.Substring(p_StartIndex,
  471. ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
  472. }
  473. }
  474. if (p_Length >= 0)
  475. {
  476. byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);
  477. //当字符串长度大于起始位置
  478. if (bsSrcString.Length > p_StartIndex)
  479. {
  480. int p_EndIndex = bsSrcString.Length;
  481. //当要截取的长度在字符串的有效长度范围内
  482. if (bsSrcString.Length > (p_StartIndex + p_Length))
  483. {
  484. p_EndIndex = p_Length + p_StartIndex;
  485. }
  486. else
  487. { //当不在有效范围内时,只取到字符串的结尾
  488. p_Length = bsSrcString.Length - p_StartIndex;
  489. p_TailString = "";
  490. }
  491. int nRealLength = p_Length;
  492. int[] anResultFlag = new int[p_Length];
  493. byte[] bsResult = null;
  494. int nFlag = 0;
  495. for (int i = p_StartIndex; i < p_EndIndex; i++)
  496. {
  497. if (bsSrcString[i] > 127)
  498. {
  499. nFlag++;
  500. if (nFlag == 3)
  501. {
  502. nFlag = 1;
  503. }
  504. }
  505. else
  506. {
  507. nFlag = 0;
  508. }
  509. anResultFlag[i] = nFlag;
  510. }
  511. if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
  512. {
  513. nRealLength = p_Length + 1;
  514. }
  515. bsResult = new byte[nRealLength];
  516. Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength);
  517. myResult = Encoding.Default.GetString(bsResult);
  518. myResult = myResult + p_TailString;
  519. }
  520. }
  521. return myResult;
  522. }
  523. /// <summary>
  524. /// 自定义的替换字符串函数
  525. /// </summary>
  526. public static string ReplaceString(string SourceString, string SearchString, string ReplaceString, bool IsCaseInsensetive)
  527. {
  528. return Regex.Replace(SourceString, Regex.Escape(SearchString), ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
  529. }
  530. /// <summary>
  531. /// 生成指定数量的html空格符号
  532. /// </summary>
  533. public static string Spaces(int nSpaces)
  534. {
  535. StringBuilder sb = new StringBuilder();
  536. for (int i = 0; i < nSpaces; i++)
  537. {
  538. sb.Append(" &nbsp;&nbsp;");
  539. }
  540. return sb.ToString();
  541. }
  542. /// <summary>
  543. /// 检测是否符合email格式
  544. /// </summary>
  545. /// <param name="strEmail">要判断的email字符串</param>
  546. /// <returns>判断结果</returns>
  547. public static bool IsValidEmail(string strEmail)
  548. {
  549. return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
  550. }
  551. public static bool IsValidDoEmail(string strEmail)
  552. {
  553. return Regex.IsMatch(strEmail, @"^@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
  554. }
  555. /// <summary>
  556. /// 检测是否是正确的Url
  557. /// </summary>
  558. /// <param name="strUrl">要验证的Url</param>
  559. /// <returns>判断结果</returns>
  560. public static bool IsURL(string strUrl)
  561. {
  562. return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
  563. }
  564. public static string GetEmailHostName(string strEmail)
  565. {
  566. if (strEmail.IndexOf("@") < 0)
  567. {
  568. return "";
  569. }
  570. return strEmail.Substring(strEmail.LastIndexOf("@")).ToLower();
  571. }
  572. /// <summary>
  573. /// 判断是否为base64字符串
  574. /// </summary>
  575. /// <param name="str"></param>
  576. /// <returns></returns>
  577. public static bool IsBase64String(string str)
  578. {
  579. //A-Z, a-z, 0-9, +, /, =
  580. return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]");
  581. }
  582. /// <summary>
  583. /// 检测是否有Sql危险字符
  584. /// </summary>
  585. /// <param name="str">要判断字符串</param>
  586. /// <returns>判断结果</returns>
  587. public static bool IsSafeSqlString(string str)
  588. {
  589. return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
  590. }
  591. /// <summary>
  592. /// 检测是否有危险的可能用于链接的字符串
  593. /// </summary>
  594. /// <param name="str">要判断字符串</param>
  595. /// <returns>判断结果</returns>
  596. public static bool IsSafeUserInfoString(string str)
  597. {
  598. return !Regex.IsMatch(str, @"^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^Guest");
  599. }
  600. /// <summary>
  601. /// 清理字符串
  602. /// </summary>
  603. public static string CleanInput(string strIn)
  604. {
  605. return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
  606. }
  607. /// <summary>
  608. /// 返回URL中结尾的文件名
  609. /// </summary>
  610. public static string GetFilename(string url)
  611. {
  612. if (url == null)
  613. {
  614. return "";
  615. }
  616. string[] strs1 = url.Split(new char[] { '/' });
  617. return strs1[strs1.Length - 1].Split(new char[] { '?' })[0];
  618. }
  619. /// <summary>
  620. /// 根据阿拉伯数字返回月份的名称(可更改为某种语言)
  621. /// </summary>
  622. public static string[] Monthes
  623. {
  624. get
  625. {
  626. return new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  627. }
  628. }
  629. /// <summary>
  630. /// 替换回车换行符为html换行符
  631. /// </summary>
  632. public static string StrFormat(string str)
  633. {
  634. string str2;
  635. if (str == null)
  636. {
  637. str2 = "";
  638. }
  639. else
  640. {
  641. str = str.Replace("\r\n", "<br />");
  642. str = str.Replace("\n", "<br />");
  643. str2 = str;
  644. }
  645. return str2;
  646. }
  647. /// <summary>
  648. /// 返回标准日期格式string
  649. /// </summary>
  650. public static string GetDate()
  651. {
  652. return DateTime.Now.ToString("yyyy-MM-dd");
  653. }
  654. /// <summary>
  655. /// 返回指定日期格式
  656. /// </summary>
  657. public static string GetDate(string datetimestr, string replacestr)
  658. {
  659. if (datetimestr == null)
  660. {
  661. return replacestr;
  662. }
  663. if (datetimestr.Equals(""))
  664. {
  665. return replacestr;
  666. }
  667. try
  668. {
  669. datetimestr = Convert.ToDateTime(datetimestr).ToString("yyyy-MM-dd").Replace("1900-01-01", replacestr);
  670. }
  671. catch
  672. {
  673. return replacestr;
  674. }
  675. return datetimestr;
  676. }
  677. /// <summary>
  678. /// 返回标准时间格式string
  679. /// </summary>
  680. public static string GetTime()
  681. {
  682. return DateTime.Now.ToString("HH:mm:ss");
  683. }
  684. /// <summary>
  685. /// 返回标准时间格式string
  686. /// </summary>
  687. public static string GetDateTime()
  688. {
  689. return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  690. }
  691. /// <summary>
  692. /// 返回相对于当前时间的相对天数
  693. /// </summary>
  694. public static string GetDateTime(int relativeday)
  695. {
  696. return DateTime.Now.AddDays(relativeday).ToString("yyyy-MM-dd HH:mm:ss");
  697. }
  698. /// <summary>
  699. /// 返回标准时间格式string
  700. /// </summary>
  701. public static string GetDateTimeF()
  702. {
  703. return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff");
  704. }
  705. /// <summary>
  706. /// 返回标准时间
  707. /// </sumary>
  708. public static string GetStandardDateTime(string fDateTime, string formatStr)
  709. {
  710. if (fDateTime == "0000-0-0 0:00:00")
  711. {
  712. return fDateTime;
  713. }
  714. DateTime s = Convert.ToDateTime(fDateTime);
  715. return s.ToString(formatStr);
  716. }
  717. /// <summary>
  718. /// 返回标准时间 yyyy-MM-dd HH:mm:ss
  719. /// </sumary>
  720. public static string GetStandardDateTime(string fDateTime)
  721. {
  722. return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss");
  723. }
  724. /// <summary>
  725. ///
  726. /// </summary>
  727. /// <returns></returns>
  728. public static bool IsTime(string timeval)
  729. {
  730. return Regex.IsMatch(timeval, @"^((([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])(:[0-5]?[0-9])?)$");
  731. }
  732. /// <summary>
  733. /// 改正sql语句中的转义字符
  734. /// </summary>
  735. public static string mashSQL(string str)
  736. {
  737. string str2;
  738. if (str == null)
  739. {
  740. str2 = "";
  741. }
  742. else
  743. {
  744. str = str.Replace("\'", "'");
  745. str2 = str;
  746. }
  747. return str2;
  748. }
  749. /// <summary>
  750. /// 替换sql语句中的有问题符号
  751. /// </summary>
  752. public static string ChkSQL(string str)
  753. {
  754. string str2;
  755. if (str == null)
  756. {
  757. str2 = "";
  758. }
  759. else
  760. {
  761. str = str.Replace("'", "''");
  762. str2 = str;
  763. }
  764. return str2;
  765. }
  766. /// <summary>
  767. /// 分割字符串
  768. /// </summary>
  769. public static string[] SplitString(string strContent, string strSplit)
  770. {
  771. if (strContent.IndexOf(strSplit) < 0)
  772. {
  773. string[] tmp = { strContent };
  774. return tmp;
  775. }
  776. return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
  777. }
  778. /// <summary>
  779. /// 分割字符串
  780. /// </summary>
  781. /// <returns></returns>
  782. public static string[] SplitString(string strContent, string strSplit, int p_3)
  783. {
  784. string[] result = new string[p_3];
  785. string[] splited = SplitString(strContent, strSplit);
  786. for (int i = 0; i < p_3; i++)
  787. {
  788. if (i < splited.Length)
  789. result[i] = splited[i];
  790. else
  791. result[i] = string.Empty;
  792. }
  793. return result;
  794. }
  795. /// <summary>
  796. /// 替换html字符
  797. /// </summary>
  798. public static string EncodeHtml(string strHtml)
  799. {
  800. if (strHtml != "")
  801. {
  802. strHtml = strHtml.Replace(",", "&def");
  803. strHtml = strHtml.Replace("'", "&dot");
  804. strHtml = strHtml.Replace(";", "&dec");
  805. return strHtml;
  806. }
  807. return "";
  808. }
  809. //public static string ClearHtml(string strHtml)
  810. //{
  811. // if (strHtml != "")
  812. // {
  813. // r = Regex.Replace(@"<\/?[^>]*>",RegexOptions.IgnoreCase);
  814. // for (m = r.Match(strHtml); m.Success; m = m.NextMatch())
  815. // {
  816. // strHtml = strHtml.Replace(m.Groups[0].ToString(),"");
  817. // }
  818. // }
  819. // return strHtml;
  820. //}
  821. /// <summary>
  822. /// 进行指定的替换(脏字过滤)
  823. /// </summary>
  824. public static string StrFilter(string str, string bantext)
  825. {
  826. string text1 = "";
  827. string text2 = "";
  828. string[] textArray1 = SplitString(bantext, "\r\n");
  829. for (int num1 = 0; num1 < textArray1.Length; num1++)
  830. {
  831. text1 = textArray1[num1].Substring(0, textArray1[num1].IndexOf("="));
  832. text2 = textArray1[num1].Substring(textArray1[num1].IndexOf("=") + 1);
  833. str = str.Replace(text1, text2);
  834. }
  835. return str;
  836. }
  837. /// <summary>
  838. /// 返回 HTML 字符串的编码结果
  839. /// </summary>
  840. /// <param name="str">字符串</param>
  841. /// <returns>编码结果</returns>
  842. public static string HtmlEncode(string str)
  843. {
  844. return HttpUtility.HtmlEncode(str);
  845. }
  846. /// <summary>
  847. /// 返回 HTML 字符串的解码结果
  848. /// </summary>
  849. /// <param name="str">字符串</param>
  850. /// <returns>解码结果</returns>
  851. public static string HtmlDecode(string str)
  852. {
  853. return HttpUtility.HtmlDecode(str);
  854. }
  855. /// <summary>
  856. /// 返回 URL 字符串的编码结果
  857. /// </summary>
  858. /// <param name="str">字符串</param>
  859. /// <returns>编码结果</returns>
  860. public static string UrlEncode(string str)
  861. {
  862. return HttpUtility.UrlEncode(str);
  863. }
  864. /// <summary>
  865. /// 返回 URL 字符串的编码结果
  866. /// </summary>
  867. /// <param name="str">字符串</param>
  868. /// <returns>解码结果</returns>
  869. public static string UrlDecode(string str)
  870. {
  871. return HttpUtility.UrlDecode(str);
  872. }
  873. /// <summary>
  874. /// 返回指定目录下的非 UTF8 字符集文件
  875. /// </summary>
  876. /// <param name="Path">路径</param>
  877. /// <returns>文件名的字符串数组</returns>
  878. public static string[] FindNoUTF8File(string Path)
  879. {
  880. //System.IO.StreamReader reader = null;
  881. StringBuilder filelist = new StringBuilder();
  882. DirectoryInfo Folder = new DirectoryInfo(Path);
  883. //System.IO.DirectoryInfo[] subFolders = Folder.GetDirectories();
  884. /*
  885. for (int i=0;i<subFolders.Length;i++)
  886. {
  887. FindNoUTF8File(subFolders[i].FullName);
  888. }
  889. */
  890. FileInfo[] subFiles = Folder.GetFiles();
  891. for (int j = 0; j < subFiles.Length; j++)
  892. {
  893. if (subFiles[j].Extension.ToLower().Equals(".htm"))
  894. {
  895. FileStream fs = new FileStream(subFiles[j].FullName, FileMode.Open, FileAccess.Read);
  896. bool bUtf8 = IsUTF8(fs);
  897. fs.Close();
  898. if (!bUtf8)
  899. {
  900. filelist.Append(subFiles[j].FullName);
  901. filelist.Append("\r\n");
  902. }
  903. }
  904. }
  905. return Utils.SplitString(filelist.ToString(), "\r\n");
  906. }
  907. //0000 0000-0000 007F - 0xxxxxxx (ascii converts to 1 octet!)
  908. //0000 0080-0000 07FF - 110xxxxx 10xxxxxx ( 2 octet format)
  909. //0000 0800-0000 FFFF - 1110xxxx 10xxxxxx 10xxxxxx (3 octet format)
  910. /// <summary>
  911. /// 判断文件流是否为UTF8字符集
  912. /// </summary>
  913. /// <param name="sbInputStream">文件流</param>
  914. /// <returns>判断结果</returns>
  915. private static bool IsUTF8(FileStream sbInputStream)
  916. {
  917. int i;
  918. byte cOctets; // octets to go in this UTF-8 encoded character
  919. byte chr;
  920. bool bAllAscii = true;
  921. long iLen = sbInputStream.Length;
  922. cOctets = 0;
  923. for (i = 0; i < iLen; i++)
  924. {
  925. chr = (byte)sbInputStream.ReadByte();
  926. if ((chr & 0x80) != 0) bAllAscii = false;
  927. if (cOctets == 0)
  928. {
  929. if (chr >= 0x80)
  930. {
  931. do
  932. {
  933. chr <<= 1;
  934. cOctets++;
  935. }
  936. while ((chr & 0x80) != 0);
  937. cOctets--;
  938. if (cOctets == 0) return false;
  939. }
  940. }
  941. else
  942. {
  943. if ((chr & 0xC0) != 0x80)
  944. {
  945. return false;
  946. }
  947. cOctets--;
  948. }
  949. }
  950. if (cOctets > 0)
  951. {
  952. return false;
  953. }
  954. if (bAllAscii)
  955. {
  956. return false;
  957. }
  958. return true;
  959. }
  960. /// <summary>
  961. /// 格式化字节数字符串
  962. /// </summary>
  963. /// <param name="bytes"></param>
  964. /// <returns></returns>
  965. public static string FormatBytesStr(int bytes)
  966. {
  967. if (bytes > 1073741824)
  968. {
  969. return ((double)(bytes / 1073741824)).ToString("0") + "G";
  970. }
  971. if (bytes > 1048576)
  972. {
  973. return ((double)(bytes / 1048576)).ToString("0") + "M";
  974. }
  975. if (bytes > 1024)
  976. {
  977. return ((double)(bytes / 1024)).ToString("0") + "K";
  978. }
  979. return bytes.ToString() + "Bytes";
  980. }
  981. /// <summary>
  982. /// 返回相差的秒数
  983. /// </summary>
  984. /// <param name="Time"></param>
  985. /// <param name="Sec"></param>
  986. /// <returns></returns>
  987. public static int StrDateDiffSeconds(string Time, int Sec)
  988. {
  989. TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec);
  990. if (ts.TotalSeconds > int.MaxValue)
  991. {
  992. return int.MaxValue;
  993. }
  994. else if (ts.TotalSeconds < int.MinValue)
  995. {
  996. return int.MinValue;
  997. }
  998. return (int)ts.TotalSeconds;
  999. }
  1000. /// <summary>
  1001. /// 返回相差的分钟数
  1002. /// </summary>
  1003. /// <param name="time"></param>
  1004. /// <param name="minutes"></param>
  1005. /// <returns></returns>
  1006. public static int StrDateDiffMinutes(string time, int minutes)
  1007. {
  1008. if (time == "" || time == null)
  1009. return 1;
  1010. TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes);
  1011. if (ts.TotalMinutes > int.MaxValue)
  1012. {
  1013. return int.MaxValue;
  1014. }
  1015. else if (ts.TotalMinutes < int.MinValue)
  1016. {
  1017. return int.MinValue;
  1018. }
  1019. return (int)ts.TotalMinutes;
  1020. }
  1021. /// <summary>
  1022. /// 返回相差的小时数
  1023. /// </summary>
  1024. /// <param name="time"></param>
  1025. /// <param name="hours"></param>
  1026. /// <returns></returns>
  1027. public static int StrDateDiffHours(string time, int hours)
  1028. {
  1029. if (time == "" || time == null)
  1030. return 1;
  1031. TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours);
  1032. if (ts.TotalHours > int.MaxValue)
  1033. {
  1034. return int.MaxValue;
  1035. }
  1036. else if (ts.TotalHours < int.MinValue)
  1037. {
  1038. return int.MinValue;
  1039. }
  1040. return (int)ts.TotalHours;
  1041. }
  1042. /// <summary>
  1043. /// 建立文件夹
  1044. /// </summary>
  1045. /// <param name="name"></param>
  1046. /// <returns></returns>
  1047. public static bool CreateDir(string name)
  1048. {
  1049. return Utils.MakeSureDirectoryPathExists(name);
  1050. }
  1051. /// <summary>
  1052. /// 为脚本替换特殊字符串
  1053. /// </summary>
  1054. /// <param name="str"></param>
  1055. /// <returns></returns>
  1056. public static string ReplaceStrToScript(string str)
  1057. {
  1058. str = str.Replace("\\", "\\\\");
  1059. str = str.Replace("'", "\\'");
  1060. str = str.Replace("\"", "\\\"");
  1061. return str;
  1062. }
  1063. /// <summary>
  1064. /// 是否为ip
  1065. /// </summary>
  1066. /// <param name="ip"></param>
  1067. /// <returns></returns>
  1068. public static bool IsIP(string ip)
  1069. {
  1070. 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?)$");
  1071. }
  1072. public static bool IsIPSect(string ip)
  1073. {
  1074. return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){2}((2[0-4]\d|25[0-5]|[01]?\d\d?|\*)\.)(2[0-4]\d|25[0-5]|[01]?\d\d?|\*)$");
  1075. }
  1076. /// <summary>
  1077. /// 返回指定IP是否在指定的IP数组所限定的范围内, IP数组内的IP地址可以使用*表示该IP段任意, 例如192.168.1.*
  1078. /// </summary>
  1079. /// <param name="ip"></param>
  1080. /// <param name="iparray"></param>
  1081. /// <returns></returns>
  1082. public static bool InIPArray(string ip, string[] iparray)
  1083. {
  1084. string[] userip = Utils.SplitString(ip, @".");
  1085. for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++)
  1086. {
  1087. string[] tmpip = Utils.SplitString(iparray[ipIndex], @".");
  1088. int r = 0;
  1089. for (int i = 0; i < tmpip.Length; i++)
  1090. {
  1091. if (tmpip[i] == "*")
  1092. {
  1093. return true;
  1094. }
  1095. if (userip.Length > i)
  1096. {
  1097. if (tmpip[i] == userip[i])
  1098. {
  1099. r++;
  1100. }
  1101. else
  1102. {
  1103. break;
  1104. }
  1105. }
  1106. else
  1107. {
  1108. break;
  1109. }
  1110. }
  1111. if (r == 4)
  1112. {
  1113. return true;
  1114. }
  1115. }
  1116. return false;
  1117. }
  1118. /// <summary>
  1119. /// 获得Assembly版本号
  1120. /// </summary>
  1121. /// <returns></returns>
  1122. public static string GetAssemblyVersion()
  1123. {
  1124. return string.Format("{0}.{1}.{2}", AssemblyFileVersion.FileMajorPart, AssemblyFileVersion.FileMinorPart, AssemblyFileVersion.FileBuildPart);
  1125. }
  1126. /// <summary>
  1127. /// 获得Assembly产品名称
  1128. /// </summary>
  1129. /// <returns></returns>
  1130. public static string GetAssemblyProductName()
  1131. {
  1132. return AssemblyFileVersion.ProductName;
  1133. }
  1134. /// <summary>
  1135. /// 获得Assembly产品版权
  1136. /// </summary>
  1137. /// <returns></returns>
  1138. public static string GetAssemblyCopyright()
  1139. {
  1140. return AssemblyFileVersion.LegalCopyright;
  1141. }
  1142. /// <summary>
  1143. /// 创建目录
  1144. /// </summary>
  1145. /// <param name="name">名称</param>
  1146. /// <returns>创建是否成功</returns>
  1147. [DllImport("dbgHelp", SetLastError = true)]
  1148. private static extern bool MakeSureDirectoryPathExists(string name);
  1149. /// <summary>
  1150. /// 写cookie值
  1151. /// </summary>
  1152. /// <param name="strName">名称</param>
  1153. /// <param name="strValue">值</param>
  1154. public static void WriteCookie(string strName, string strValue)
  1155. {
  1156. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1157. if (cookie == null)
  1158. {
  1159. cookie = new HttpCookie(strName);
  1160. }
  1161. cookie.Value = strValue;
  1162. HttpContext.Current.Response.AppendCookie(cookie);
  1163. }
  1164. /// <summary>
  1165. /// 写cookie值
  1166. /// </summary>
  1167. /// <param name="strName">名称</param>
  1168. /// <param name="strValue">值</param>
  1169. /// <param name="strValue">过期时间(分钟)</param>
  1170. public static void WriteCookie(string strName, string strValue, int expires)
  1171. {
  1172. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  1173. if (cookie == null)
  1174. {
  1175. cookie = new HttpCookie(strName);
  1176. }
  1177. cookie.Value = strValue;
  1178. cookie.Expires = DateTime.Now.AddMinutes(expires);
  1179. HttpContext.Current.Response.AppendCookie(cookie);
  1180. }
  1181. /// <summary>
  1182. /// 读cookie值
  1183. /// </summary>
  1184. /// <param name="strName">名称</param>
  1185. /// <returns>cookie值</returns>
  1186. public static string GetCookie(string strName)
  1187. {
  1188. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  1189. {
  1190. return HttpContext.Current.Request.Cookies[strName].Value.ToString();
  1191. }
  1192. return "";
  1193. }
  1194. /// <summary>
  1195. /// 得到论坛的真实路径
  1196. /// </summary>
  1197. /// <returns></returns>
  1198. public static string GetTrueForumPath()
  1199. {
  1200. string forumPath = HttpContext.Current.Request.Path;
  1201. if (forumPath.LastIndexOf("/") != forumPath.IndexOf("/"))
  1202. {
  1203. forumPath = forumPath.Substring(forumPath.IndexOf("/"), forumPath.LastIndexOf("/") + 1);
  1204. }
  1205. else
  1206. {
  1207. forumPath = "/";
  1208. }
  1209. return forumPath;
  1210. }
  1211. /// <summary>
  1212. /// 判断字符串是否是yy-mm-dd字符串
  1213. /// </summary>
  1214. /// <param name="str">待判断字符串</param>
  1215. /// <returns>判断结果</returns>
  1216. public static bool IsDateString(string str)
  1217. {
  1218. return Regex.IsMatch(str, @"(\d{4})-(\d{1,2})-(\d{1,2})");
  1219. }
  1220. /// <summary>
  1221. /// 移除Html标记
  1222. /// </summary>
  1223. /// <param name="content"></param>
  1224. /// <returns></returns>
  1225. public static string RemoveHtml(string content)
  1226. {
  1227. string regexstr = @"<[^>]*>";
  1228. return Regex.Replace(content, regexstr, string.Empty, RegexOptions.IgnoreCase);
  1229. }
  1230. /// <summary>
  1231. /// 过滤HTML中的不安全标签
  1232. /// </summary>
  1233. /// <param name="content"></param>
  1234. /// <returns></returns>
  1235. public static string RemoveUnsafeHtml(string content)
  1236. {
  1237. content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
  1238. content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
  1239. return content;
  1240. }
  1241. /// <summary>
  1242. /// 将用户组Title中的font标签去掉
  1243. /// </summary>
  1244. /// <param name="title">用户组Title</param>
  1245. /// <returns></returns>
  1246. public static string RemoveFontTag(string title)
  1247. {
  1248. Match m = RegexFont.Match(title);
  1249. if (m.Success)
  1250. {
  1251. return m.Groups[1].Value;
  1252. }
  1253. return title;
  1254. }
  1255. /// <summary>
  1256. /// 从HTML中获取文本,保留br,p,img
  1257. /// </summary>
  1258. /// <param name="HTML"></param>
  1259. /// <returns></returns>
  1260. public static string GetTextFromHTML(string HTML)
  1261. {
  1262. System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"</?(?!br|/?p|img)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  1263. return regEx.Replace(HTML, "");
  1264. }
  1265. public static string AdDeTime(int times)
  1266. {
  1267. string newtime = (DateTime.Now).AddMinutes(times).ToString();
  1268. return newtime;
  1269. }
  1270. /// <summary>
  1271. /// 验证是否为正整数
  1272. /// </summary>
  1273. /// <param name="str"></param>
  1274. /// <returns></returns>
  1275. public static bool IsInt(string str)
  1276. {
  1277. return Regex.IsMatch(str, @"^[0-9]*$");
  1278. }
  1279. public static bool IsRuleTip(Hashtable NewHash, string ruletype, out string key)
  1280. {
  1281. key = "";
  1282. foreach (DictionaryEntry str in NewHash)
  1283. {
  1284. try
  1285. {
  1286. string[] single = SplitString(str.Value.ToString(), "\r\n");
  1287. foreach (string strs in single)
  1288. {
  1289. if (strs != "")
  1290. switch (ruletype.Trim().ToLower())
  1291. {
  1292. case "email":
  1293. if (IsValidDoEmail(strs.ToString()) == false)
  1294. throw new Exception();
  1295. break;
  1296. case "ip":
  1297. if (IsIPSect(strs.ToString()) == false)
  1298. throw new Exception();
  1299. break;
  1300. case "timesect":
  1301. string[] splitetime = strs.Split('-');
  1302. if (Utils.IsTime(splitetime[1].ToString()) == false || Utils.IsTime(splitetime[0].ToString()) == false)
  1303. throw new Exception();
  1304. break;
  1305. }
  1306. }
  1307. }
  1308. catch
  1309. {
  1310. key = str.Key.ToString();
  1311. return false;
  1312. }
  1313. }
  1314. return true;
  1315. }
  1316. /// <summary>
  1317. /// 删除最后一个字符
  1318. /// </summary>
  1319. /// <param name="str"></param>
  1320. /// <returns></returns>
  1321. public static string ClearLastChar(string str)
  1322. {
  1323. if (str == "")
  1324. return "";
  1325. else
  1326. return str.Substring(0, str.Length - 1);
  1327. }
  1328. /// <summary>
  1329. /// 备份文件
  1330. /// </summary>
  1331. /// <param name="sourceFileName">源文件名</param>
  1332. /// <param name="destFileName">目标文件名</param>
  1333. /// <param name="overwrite">当目标文件存在时是否覆盖</param>
  1334. /// <returns>操作是否成功</returns>
  1335. public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite)
  1336. {
  1337. if (!System.IO.File.Exists(sourceFileName))
  1338. {
  1339. throw new FileNotFoundException(sourceFileName + "文件不存在!");
  1340. }
  1341. if (!overwrite && System.IO.File.Exists(destFileName))
  1342. {
  1343. return false;
  1344. }
  1345. try
  1346. {
  1347. System.IO.File.Copy(sourceFileName, destFileName, true);
  1348. return true;
  1349. }
  1350. catch (Exception e)
  1351. {
  1352. throw e;
  1353. }
  1354. }
  1355. /// <summary>
  1356. /// 备份文件,当目标文件存在时覆盖
  1357. /// </summary>
  1358. /// <param name="sourceFileName">源文件名</param>
  1359. /// <param name="destFileName">目标文件名</param>
  1360. /// <returns>操作是否成功</returns>
  1361. public static bool BackupFile(string sourceFileName, string destFileName)
  1362. {
  1363. return BackupFile(sourceFileName, destFileName, true);
  1364. }
  1365. /// <summary>
  1366. /// 恢复文件
  1367. /// </summary>
  1368. /// <param name="backupFileName">备份文件名</param>
  1369. /// <param name="targetFileName">要恢复的文件名</param>
  1370. /// <param name="backupTargetFileName">要恢复文件再次备份的名称,如果为null,则不再备份恢复文件</param>
  1371. /// <returns>操作是否成功</returns>
  1372. public static bool RestoreFile(string backupFileName, string targetFileName, string backupTargetFileName)
  1373. {
  1374. try
  1375. {
  1376. if (!System.IO.File.Exists(backupFileName))
  1377. {
  1378. throw new FileNotFoundException(backupFileName + "文件不存在!");
  1379. }
  1380. if (backupTargetFileName != null)
  1381. {
  1382. if (!System.IO.File.Exists(targetFileName))
  1383. {
  1384. throw new FileNotFoundException(targetFileName + "文件不存在!无法备份此文件!");
  1385. }
  1386. else
  1387. {
  1388. System.IO.File.Copy(targetFileName, backupTargetFileName, true);
  1389. }
  1390. }
  1391. System.IO.File.Delete(targetFileName);
  1392. System.IO.File.Copy(backupFileName, targetFileName);
  1393. }
  1394. catch (Exception e)
  1395. {
  1396. throw e;
  1397. }
  1398. return true;
  1399. }
  1400. public static bool RestoreFile(string backupFileName, string targetFileName)
  1401. {
  1402. return RestoreFile(backupFileName, targetFileName, null);
  1403. }
  1404. /// <summary>
  1405. /// 获取记录模板id的cookie名称
  1406. /// </summary>
  1407. /// <returns></returns>
  1408. public static string GetTemplateCookieName()
  1409. {
  1410. return TemplateCookieName;
  1411. }
  1412. /// <summary>
  1413. /// 将全角数字转换为数字
  1414. /// </summary>
  1415. /// <param name="SBCCase"></param>
  1416. /// <returns></returns>
  1417. public static string SBCCaseToNumberic(string SBCCase)
  1418. {
  1419. char[] c = SBCCase.ToCharArray();
  1420. for (int i = 0; i < c.Length; i++)
  1421. {
  1422. byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
  1423. if (b.Length == 2)
  1424. {
  1425. if (b[1] == 255)
  1426. {
  1427. b[0] = (byte)(b[0] + 32);
  1428. b[1] = 0;
  1429. c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
  1430. }
  1431. }
  1432. }
  1433. return new string(c);
  1434. }
  1435. /// <summary>
  1436. /// 将字符串转换为Color
  1437. /// </summary>
  1438. /// <param name="color"></param>
  1439. /// <returns></returns>
  1440. public static Color ToColor(string color)
  1441. {
  1442. int red, green, blue = 0;
  1443. char[] rgb;
  1444. color = color.TrimStart('#');
  1445. color = Regex.Replace(color.ToLower(), "[g-zG-Z]", "");
  1446. switch (color.Length)
  1447. {
  1448. case 3:
  1449. rgb = color.ToCharArray();
  1450. red = Convert.ToInt32(rgb[0].ToString() + rgb[0].ToString(), 16);
  1451. green = Convert.ToInt32(rgb[1].ToString() + rgb[1].ToString(), 16);
  1452. blue = Convert.ToInt32(rgb[2].ToString() + rgb[2].ToString(), 16);
  1453. return Color.FromArgb(red, green, blue);
  1454. case 6:
  1455. rgb = color.ToCharArray();
  1456. red = Convert.ToInt32(rgb[0].ToString() + rgb[1].ToString(), 16);
  1457. green = Convert.ToInt32(rgb[2].ToString() + rgb[3].ToString(), 16);
  1458. blue = Convert.ToInt32(rgb[4].ToString() + rgb[5].ToString(), 16);
  1459. return Color.FromArgb(red, green, blue);
  1460. default:
  1461. return Color.FromName(color);
  1462. }
  1463. }
  1464. public static void CheckSql()
  1465. {
  1466. string jk1986_sql = "exec↓select↓drop↓alter↓exists↓union↓order↓execute↓xp_cmdshell↓insert↓update↓delete↓declare↓sp_oacreate↓wscript.shell↓xp_regwrite";
  1467. string[] jk_sql = jk1986_sql.Split('↓');
  1468. foreach (string jk in jk_sql)
  1469. {
  1470. // -----------------------防 Post 注入-----------------------
  1471. if (System.Web.HttpContext.Current.Request.Form != null)
  1472. {
  1473. for (int k = 0; k < System.Web.HttpContext.Current.Request.Form.Count; k++)
  1474. {
  1475. string getsqlkey = System.Web.HttpContext.Current.Request.Form.Keys[k];
  1476. if (getsqlkey != "__VIEWSTATE")
  1477. {
  1478. string getip;
  1479. if (System.Web.HttpContext.Current.Request.Form[getsqlkey].ToLower().Contains(jk) == true)
  1480. {
  1481. System.Web.HttpContext.Current.Response.Write("<script Language=JavaScript>alert('防注入程序提示您,请勿提交非法字符!');</" + "script>");
  1482. System.Web.HttpContext.Current.Response.Write("非法操作!系统做了如下记录 ↓" + "<br>");
  1483. if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
  1484. {
  1485. getip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  1486. }
  1487. else
  1488. {
  1489. getip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  1490. }
  1491. System.Web.HttpContext.Current.Response.Write("操 作 I P :" + getip + "<br>");
  1492. System.Web.HttpContext.Current.Response.Write("操 作 时 间:" + DateTime.Now.ToString() + "<br>");
  1493. System.Web.HttpContext.Current.Response.Write("操 作 页 面:" + System.Web.HttpContext.Current.Request.ServerVariables["URL"] + "<br>");
  1494. System.Web.HttpContext.Current.Response.Write("提 交 方 式:P O S T " + "<br>");
  1495. System.Web.HttpContext.Current.Response.Write("提 交 参 数:" + jk + "<br>");
  1496. System.Web.HttpContext.Current.Response.Write("提 交 数 据:" + System.Web.HttpContext.Current.Request.Form[getsqlkey].ToLower() + "<br>");
  1497. System.Web.HttpContext.Current.Response.End();
  1498. }
  1499. }
  1500. }
  1501. }
  1502. // -----------------------防 GET 注入-----------------------
  1503. if (System.Web.HttpContext.Current.Request.QueryString != null)
  1504. {
  1505. for (int k = 0; k < System.Web.HttpContext.Current.Request.QueryString.Count; k++)
  1506. {
  1507. string getsqlkey = System.Web.HttpContext.Current.Request.QueryString.Keys[k];
  1508. string getip;
  1509. if (getsqlkey != "__VIEWSTATE")
  1510. {
  1511. if (System.Web.HttpContext.Current.Request.QueryString[getsqlkey].ToLower().Contains(jk) == true)
  1512. {
  1513. System.Web.HttpContext.Current.Response.Write("<script Language=JavaScript>alert('防注入程序提示您,请勿提交非法字符!');</" + "script>");
  1514. System.Web.HttpContext.Current.Response.Write("非法操作!系统做了如下记录 ↓" + "<br>");
  1515. if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
  1516. {
  1517. getip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  1518. }
  1519. else
  1520. {
  1521. getip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  1522. }
  1523. System.Web.HttpContext.Current.Response.Write("操 作 I P :" + getip + "<br>");
  1524. System.Web.HttpContext.Current.Response.Write("操 作 时 间:" + DateTime.Now.ToString() + "<br>");
  1525. System.Web.HttpContext.Current.Response.Write("操 作 页 面:" + System.Web.HttpContext.Current.Request.ServerVariables["URL"] + "<br>");
  1526. System.Web.HttpContext.Current.Response.Write("提 交 方 式:G E T " + "<br>");
  1527. System.Web.HttpContext.Current.Response.Write("提 交 参 数:" + jk + "<br>");
  1528. System.Web.HttpContext.Current.Response.Write("提 交 数 据:" + System.Web.HttpContext.Current.Request.QueryString[getsqlkey].ToLower() + "<br>");
  1529. System.Web.HttpContext.Current.Response.End();
  1530. }
  1531. }
  1532. }
  1533. }
  1534. // -----------------------防 Cookies 注入-----------------------
  1535. if (System.Web.HttpContext.Current.Request.Cookies != null)
  1536. {
  1537. for (int k = 0; k < System.Web.HttpContext.Current.Request.Cookies.Count; k++)
  1538. {
  1539. string getsqlkey = System.Web.HttpContext.Current.Request.Cookies.Keys[k];
  1540. string getip;
  1541. if (getsqlkey != "__VIEWSTATE")
  1542. {
  1543. if (System.Web.HttpContext.Current.Request.Cookies[getsqlkey].Value.ToLower().Contains(jk) == true)
  1544. {
  1545. System.Web.HttpContext.Current.Response.Write("<script Language=JavaScript>alert('防注入程序提示您,请勿提交非法字符!');</" + "script>");
  1546. System.Web.HttpContext.Current.Response.Write("非法操作!系统做了如下记录 ↓" + "<br>");
  1547. if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
  1548. {
  1549. getip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  1550. }
  1551. else
  1552. {
  1553. getip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  1554. }
  1555. System.Web.HttpContext.Current.Response.Write("操 作 I P :" + getip + "<br>");
  1556. System.Web.HttpContext.Current.Response.Write("操 作 时 间:" + DateTime.Now.ToString() + "<br>");
  1557. System.Web.HttpContext.Current.Response.Write("操 作 页 面:" + System.Web.HttpContext.Current.Request.ServerVariables["URL"] + "<br>");
  1558. System.Web.HttpContext.Current.Response.Write("提 交 方 式: Cookies " + "<br>");
  1559. System.Web.HttpContext.Current.Response.Write("提 交 参 数:" + jk + "<br>");
  1560. System.Web.HttpContext.Current.Response.Write("提 交 数 据:" + System.Web.HttpContext.Current.Request.Cookies[getsqlkey].Value.ToLower() + "<br>");
  1561. System.Web.HttpContext.Current.Response.End();
  1562. }
  1563. }
  1564. }
  1565. }
  1566. }
  1567. }
  1568. private bool ValidateQuery(Hashtable queryConditions)
  1569. {
  1570. //构造SQL的注入关键字符
  1571. #region 字符
  1572. string[] strBadChar = {"and"
  1573. ,"exec"
  1574. ,"insert"
  1575. ,"select"
  1576. ,"delete"
  1577. ,"update"
  1578. ,"count"
  1579. ,"or"
  1580. //,"*"
  1581. ,"%"
  1582. ,":"
  1583. ,"\'"
  1584. ,"\""
  1585. ,"chr"
  1586. ,"mid"
  1587. ,"master"
  1588. ,"truncate"
  1589. ,"char"
  1590. ,"declare"
  1591. ,"SiteName"
  1592. ,"net user"
  1593. ,"xp_cmdshell"
  1594. ,"/add"
  1595. ,"exec master.dbo.xp_cmdshell"
  1596. ,"net localgroup administrators"};
  1597. #endregion
  1598. //构造正则表达式
  1599. string str_Regex = ".*(";
  1600. for (int i = 0; i < strBadChar.Length - 1; i++)
  1601. {
  1602. str_Regex += strBadChar[i] + "|";
  1603. }
  1604. str_Regex += strBadChar[strBadChar.Length - 1] + ").*";
  1605. //避免查询条件中_list情况
  1606. foreach (string str in queryConditions.Keys)
  1607. {
  1608. if (str.Substring(str.Length - 5) == "_list")
  1609. {
  1610. //去掉单引号检验
  1611. str_Regex = str_Regex.Replace("|'|", "|");
  1612. }
  1613. string tempStr = queryConditions[str].ToString();
  1614. if (Regex.Matches(tempStr.ToString(), str_Regex).Count > 0)
  1615. {
  1616. //有SQL注入字符
  1617. return true;
  1618. }
  1619. }
  1620. return false;
  1621. }
  1622. /// <summary>
  1623. /// 将对象序列化
  1624. /// </summary>
  1625. /// <param name="obj"></param>
  1626. /// <returns></returns>
  1627. private static MemoryStream Serialize(object obj)
  1628. {
  1629. try
  1630. {
  1631. BinaryFormatter formatter = new BinaryFormatter();
  1632. MemoryStream ms = new MemoryStream();
  1633. formatter.Serialize(ms, obj);
  1634. return ms;
  1635. }
  1636. catch
  1637. {
  1638. return null;
  1639. }
  1640. }
  1641. /// <summary>
  1642. /// 将DataTable转换为String型
  1643. /// </summary>
  1644. /// <param name="dt"></param>
  1645. /// <returns></returns>
  1646. public static string ConventDataTableToString(DataTable dt)
  1647. {
  1648. try
  1649. {
  1650. MemoryStream msObj = Serialize(dt);
  1651. return Convert.ToBase64String(msObj.ToArray());
  1652. }
  1653. catch
  1654. {
  1655. return null;
  1656. }
  1657. }
  1658. /// <summary>
  1659. /// 序列化
  1660. /// </summary>
  1661. /// <param name="stream"></param>
  1662. /// <returns></returns>
  1663. private static object Deserialize(Stream stream)
  1664. {
  1665. try
  1666. {
  1667. BinaryFormatter formatter = new BinaryFormatter();
  1668. return formatter.Deserialize(stream);
  1669. }
  1670. catch
  1671. {
  1672. return null;
  1673. }
  1674. }
  1675. /// <summary>
  1676. /// 将string转换为对象
  1677. /// </summary>
  1678. /// <param name="str"></param>
  1679. /// <returns></returns>
  1680. public static DataTable ConventStringToDataTable(string str)
  1681. {
  1682. try
  1683. {
  1684. byte[] byteArrayObj = Convert.FromBase64String(str);
  1685. Stream myObj = new MemoryStream(byteArrayObj);
  1686. return (DataTable)Deserialize(myObj);
  1687. }
  1688. catch
  1689. {
  1690. return null;
  1691. }
  1692. }
  1693. }
  1694. }