Utils.cs 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Runtime.InteropServices;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Web;
  10. using System.Web.UI;
  11. using Microsoft.VisualBasic;
  12. using System.Collections;
  13. using System.Collections.Generic;
  14. using System.Globalization;
  15. using System.Net;
  16. using System.Net.Mail;
  17. using System.Linq;
  18. using System.Configuration;
  19. namespace CP.Common
  20. {
  21. /// <summary>
  22. /// 工具类
  23. /// </summary>
  24. public class Utils
  25. {
  26. #region 获取Int星期值
  27. /// <summary>
  28. /// 获取int星期值
  29. /// </summary>
  30. /// <param name="StrWeek"></param>
  31. /// <returns></returns>
  32. public static int GetIntWeek(string StrWeek)
  33. {
  34. int intWeekday = -1;
  35. switch (StrWeek)
  36. {
  37. case "Monday":
  38. intWeekday = 1;
  39. break;
  40. case "Tuesday":
  41. intWeekday = 2;
  42. break;
  43. case "Wednesday":
  44. intWeekday = 3;
  45. break;
  46. case "Thursday":
  47. intWeekday = 4;
  48. break;
  49. case "Friday":
  50. intWeekday = 5;
  51. break;
  52. case "Saturday":
  53. intWeekday = 6;
  54. break;
  55. case "Sunday":
  56. intWeekday = 7;
  57. break;
  58. default:
  59. intWeekday = -1;
  60. break;
  61. }
  62. return intWeekday;
  63. }
  64. #endregion
  65. /// <summary>
  66. /// 验证是否为整数,且大于min
  67. /// </summary>
  68. /// <param name="min"></param>
  69. /// <param name="judgeStr"></param>
  70. /// <returns></returns>
  71. public static bool JudgeInt(int min, string judgeStr)
  72. {
  73. if (string.IsNullOrWhiteSpace(judgeStr))
  74. return false;
  75. int value = 0;
  76. if (!int.TryParse(judgeStr, out value))
  77. return false;
  78. if (value < min)
  79. return false;
  80. return true;
  81. }
  82. /// <summary>
  83. /// 下期奖池、投注金额
  84. /// </summary>
  85. /// <param name="min"></param>
  86. /// <param name="judgeStr"></param>
  87. /// <returns></returns>
  88. public static bool JudgeLong(int min, string judgeStr)
  89. {
  90. if (string.IsNullOrWhiteSpace(judgeStr))
  91. return false;
  92. long value = 0;
  93. if (!long.TryParse(judgeStr, out value))
  94. return false;
  95. if (value < min)
  96. return false;
  97. return true;
  98. }
  99. public static bool JudgeInt(int min,int max, string judgeStr)
  100. {
  101. if (string.IsNullOrWhiteSpace(judgeStr))
  102. return false;
  103. int value = 0;
  104. if (!int.TryParse(judgeStr, out value))
  105. return false;
  106. if (value < min)
  107. return false;
  108. if (value > max)
  109. return false;
  110. return true;
  111. }
  112. public static bool JudgeIntWithLen2(int min, int max, string judgeStr)
  113. {
  114. if (string.IsNullOrWhiteSpace(judgeStr))
  115. return false;
  116. if (judgeStr.Length != 2)
  117. return false;
  118. int value = 0;
  119. if (!int.TryParse(judgeStr, out value))
  120. return false;
  121. if (value < min)
  122. return false;
  123. if (value > max)
  124. return false;
  125. return true;
  126. }
  127. /// <summary>
  128. /// 分析开奖号,组六0、组三2、豹子3
  129. /// </summary>
  130. /// <param name="kaijianghao"></param>
  131. /// <returns></returns>
  132. public static int StatisticKaijianghao(string kaijianghao)
  133. {
  134. if (kaijianghao[0] == kaijianghao[1] && kaijianghao[0] == kaijianghao[2])
  135. return 3;
  136. else if (kaijianghao[0] != kaijianghao[1] && kaijianghao[0] != kaijianghao[2] && kaijianghao[1] != kaijianghao[2])
  137. return 0;
  138. else return 2;
  139. }
  140. public static bool JudgeInt(string value)
  141. {
  142. int ret = 0;
  143. if (!int.TryParse(value, out ret))
  144. {
  145. return false;
  146. }
  147. return true;
  148. }
  149. /// <summary>
  150. /// 邮件发送程序
  151. /// </summary>
  152. /// <param name="mail"></param>
  153. /// <returns></returns>
  154. public static bool SendMail(MailMessage mail)
  155. {
  156. bool yes = false;
  157. mail.IsBodyHtml = true;
  158. mail.SubjectEncoding = System.Text.Encoding.GetEncoding("utf-8");
  159. SmtpClient smtpClient = new SmtpClient();
  160. smtpClient.EnableSsl = false;
  161. smtpClient.Host = "smtp.exmail.qq.com";
  162. smtpClient.Port = 25;
  163. smtpClient.Credentials = new NetworkCredential("8200@6617.com", "love0021$%");
  164. try
  165. {
  166. smtpClient.Send(mail);
  167. yes = true;
  168. }
  169. catch //(Exception ex)
  170. {
  171. //System.Web.HttpContext.Current.Response.Write(ex.Message );
  172. }
  173. return yes;
  174. }
  175. /// <summary>
  176. /// 生成永不重复的字串..
  177. /// 然后md5
  178. /// </summary>
  179. /// <returns></returns>
  180. public static string GetRandomString()
  181. {
  182. string key = System.Guid.NewGuid().ToString().Replace("-", "");
  183. return MD5(key);
  184. }
  185. /// <summary>
  186. /// 返回url的根域名
  187. /// </summary>
  188. /// <param name="url"></param>
  189. /// <returns></returns>
  190. public static string GetUrlDomainName(string url)
  191. {
  192. string p = @"^https?://(?<domain>[^/]+)(/|$)";
  193. Regex reg = new Regex(p, RegexOptions.IgnoreCase);
  194. Match m = reg.Match(url);
  195. return m.Groups["domain"].Value.ToString().Trim();
  196. }
  197. /// <summary>
  198. /// 取图片源地址string[]
  199. /// </summary>
  200. /// <param name="content"></param>
  201. /// <returns></returns>
  202. public static string[] GetHtmlImageUrlList(string content)
  203. {
  204. // 定义正则表达式用来匹配 img 标签
  205. Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
  206. // 搜索匹配的字符串
  207. MatchCollection matches = regImg.Matches(content);
  208. int i = 0;
  209. string[] list = new string[matches.Count];
  210. // 取得匹配项列表
  211. foreach (Match match in matches)
  212. list[i++] = match.Groups["imgUrl"].Value.ToString().Trim();
  213. return list;
  214. }
  215. /// <summary>
  216. /// http post
  217. /// </summary>
  218. /// <param name="url"></param>
  219. /// <param name="param"></param>
  220. /// <returns></returns>
  221. public static string HttpPost(string url, string param)
  222. {
  223. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  224. request.Method = "POST";
  225. request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
  226. request.Accept = "*/*";
  227. request.Timeout = 15000;
  228. request.AllowAutoRedirect = false;
  229. StreamWriter requestStream = null;
  230. WebResponse response = null;
  231. string responseStr = null;
  232. try
  233. {
  234. requestStream = new StreamWriter(request.GetRequestStream());
  235. requestStream.Write(param);
  236. requestStream.Close();
  237. response = request.GetResponse();
  238. if (response != null)
  239. {
  240. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  241. responseStr = reader.ReadToEnd();
  242. reader.Close();
  243. }
  244. }
  245. catch (Exception)
  246. {
  247. throw;
  248. }
  249. finally
  250. {
  251. request = null;
  252. if (requestStream != null)
  253. requestStream.Close();
  254. if (response != null)
  255. response.Close();
  256. }
  257. return responseStr;
  258. }
  259. /// <summary>
  260. /// HTTP Get请求
  261. /// </summary>
  262. /// <param name="url">地址</param>
  263. /// <returns></returns>
  264. public static string HttpGet(string url)
  265. {
  266. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  267. request.Method = "GET";
  268. request.ContentType = "application/x-www-form-urlencoded";
  269. request.Accept = "*/*";
  270. request.Timeout = 15000;
  271. request.ServicePoint.Expect100Continue = false;
  272. //request.AllowAutoRedirect = false;
  273. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36";
  274. WebResponse response = null;
  275. string responseStr = string.Empty;
  276. try
  277. {
  278. response = request.GetResponse();
  279. if (response != null)
  280. {
  281. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  282. responseStr = reader.ReadToEnd();
  283. reader.Close();
  284. }
  285. }
  286. catch (WebException ex)
  287. {
  288. responseStr = "Http Get出错,出错信息:" + ex.Message;
  289. }
  290. finally
  291. {
  292. request = null;
  293. if (response != null)
  294. response.Close();
  295. }
  296. return responseStr;
  297. }
  298. /// <summary>
  299. /// 下载网络图片
  300. /// 返回二进制流
  301. /// </summary>
  302. /// <param name="url"></param>
  303. /// <returns></returns>
  304. public static byte[] GetRemoteUrlByte(string url)
  305. {
  306. if (url.IndexOf("http://") == -1)
  307. {
  308. url = "http://pic.8200.cn/" + url;
  309. }
  310. byte[] bs = null;
  311. try
  312. {
  313. System.Net.WebClient wc = new System.Net.WebClient();
  314. bs = wc.DownloadData(url);
  315. }
  316. catch { }
  317. return bs;
  318. }
  319. /// <summary>
  320. /// 根据字符长度,返回n个*号
  321. /// </summary>
  322. /// <param name="str"></param>
  323. /// <returns></returns>
  324. public static string GetStar(string str)
  325. {
  326. int len = str.Length;
  327. StringBuilder sb = new StringBuilder();
  328. for (int i = 0; i < len; i++)
  329. {
  330. sb.Append("*");
  331. }
  332. return sb.ToString();
  333. }
  334. /// <summary>
  335. /// 截取固定长度并不带html字串的方法
  336. /// </summary>
  337. /// <param name="str"></param>
  338. /// <param name="len"></param>
  339. /// <returns></returns>
  340. public static string GetCutNoHtmlString(string str, int len)
  341. {
  342. str = RemoveHtml(str);
  343. str = str.Replace("<br />", "");
  344. str = str.Replace("<br>", "");
  345. str = str.Replace("。", "");
  346. str = str.Replace(",", " ");
  347. str = str.Replace(",", " ");
  348. str = str.Replace("\r\n", "");
  349. str = str.Replace("\r", "");
  350. str = str.Replace("\n", "");
  351. str = str.Replace(" ", "");
  352. str = str.Replace("&nbsp;", " ");
  353. return CutString(str, len) + "...";
  354. }
  355. /// <summary>
  356. /// 算出数组中出现次数最多的 元素+次数
  357. /// 返回 7-3 格式
  358. /// </summary>
  359. /// <param name="array"></param>
  360. /// <returns></returns>
  361. public static string GetArrayMaxCount(object[] array)
  362. {
  363. if (array == null || array.Length == 0)
  364. return "";
  365. var groupList = array.ToList().GroupBy(a => a).Select(g => new { g.Key, count = g.Count() }).OrderByDescending(c => c.count);
  366. object maxNum = groupList.ToList()[0].Key;
  367. object maxValue = groupList.ToList()[0].count;
  368. return maxNum + "<span>(" + maxValue + ")</span>";
  369. }
  370. /// <summary>
  371. /// 构造出3d/p3的1000注所有号码
  372. /// </summary>
  373. /// <returns></returns>
  374. public static List<int> GetAllNumber()
  375. {
  376. List<int> list = new List<int>();
  377. for (int i = 0; i < 1000; i++)
  378. list.Add(i);
  379. return list;
  380. }
  381. /// <summary>
  382. /// 取站点的http://+domain部分..
  383. /// </summary>
  384. /// <returns></returns>
  385. public static string GetDomain()
  386. {
  387. string domain = "www.8200.cn";
  388. if (ConfigurationManager.AppSettings["domain"] != null)
  389. domain = ConfigurationManager.AppSettings["domain"].ToString().Trim();
  390. return "https://" + domain;
  391. //return "http://" + domain;
  392. }
  393. /// <summary>
  394. /// 读取某相对路径下的文本文件内容
  395. /// </summary>
  396. /// <param name="path">相对路径</param>
  397. /// <returns></returns>
  398. public static string ReadFile(string path)
  399. {
  400. string result = string.Empty;
  401. try
  402. {
  403. path = HttpContext.Current.Server.MapPath("/") + path;
  404. result = File.ReadAllText(path);
  405. }
  406. catch
  407. {
  408. throw;
  409. }
  410. return result;
  411. }
  412. /// <summary>
  413. /// 获得当前页面客户端的IP
  414. /// </summary>
  415. /// <returns>当前页面客户端的IP</returns>
  416. public static string GetRealIP()
  417. {
  418. string result = string.Empty;
  419. //result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  420. //if (string.IsNullOrEmpty(result))
  421. result = HttpContext.Current.Request.ServerVariables["HTTP_CDN_SRC_IP"];
  422. if (string.IsNullOrEmpty(result))
  423. result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  424. if (string.IsNullOrEmpty(result))
  425. result = HttpContext.Current.Request.UserHostAddress;
  426. if (string.IsNullOrEmpty(result) || !IsIP(result))
  427. return "127.0.0.1";
  428. return result;
  429. }
  430. /// <summary>
  431. /// 写Cookie值
  432. /// </summary>
  433. /// <param name="strName">键</param>
  434. /// <param name="strValue">名</param>
  435. /// <param name="httponly">httponly默认true</param>
  436. /// <param name="expires">默认480分钟</param>
  437. public static void WriteCookie(string strName, string strValue, int expires = 480, bool httponly = true)
  438. {
  439. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  440. if (cookie == null)
  441. {
  442. cookie = new HttpCookie(strName);
  443. }
  444. cookie.HttpOnly = httponly;
  445. //cookie.Domain = ".8200.cn";
  446. cookie.Value = HttpContext.Current.Server.UrlEncode(strValue);
  447. if (expires > 0)
  448. cookie.Expires = DateTime.Now.AddMinutes(expires);
  449. HttpContext.Current.Response.AppendCookie(cookie);
  450. }
  451. /// <summary>
  452. /// 写Cookie值
  453. /// </summary>
  454. /// <param name="strName">名称</param>
  455. /// <param name="key">键</param>
  456. /// <param name="strValue">值</param>
  457. /// <param name="expires">过期时间</param>
  458. public static void WriteCookie(string strName, string key, string strValue, int expires = 480)
  459. {
  460. HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
  461. if (cookie == null)
  462. {
  463. cookie = new HttpCookie(strName);
  464. }
  465. cookie[key] = HttpContext.Current.Server.UrlEncode(strValue);
  466. //cookie.Domain = ".8200.cn";
  467. if (expires > 0)
  468. cookie.Expires = DateTime.Now.AddMinutes(expires);
  469. HttpContext.Current.Response.AppendCookie(cookie);
  470. }
  471. /// <summary>
  472. /// 读cookie值
  473. /// </summary>
  474. /// <param name="strName">名称</param>
  475. /// <returns>cookie值</returns>
  476. public static string GetCookie(string strName)
  477. {
  478. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
  479. {
  480. //HttpContext.Current.Request.Cookies[strName].Domain = ".8200.cn";
  481. return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
  482. }
  483. return "";
  484. }
  485. /// <summary>
  486. /// 读cookie值
  487. /// </summary>
  488. /// <param name="strName">名称</param>
  489. /// <param name="key">cookie键</param>
  490. /// <returns>cookie值</returns>
  491. public static string GetCookie(string strName, string key)
  492. {
  493. if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
  494. {
  495. //HttpContext.Current.Request.Cookies[strName].Domain = ".8200.cn";
  496. return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());
  497. }
  498. return "";
  499. }
  500. /// <summary>
  501. /// 另外一个清理所有Cookie的方法
  502. /// </summary>
  503. public static void FlushAllCookie()
  504. {
  505. for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
  506. {
  507. HttpContext.Current.Response.Cookies[HttpContext.Current.Request.Cookies.Keys[i]].Expires = DateTime.Now.AddDays(-600);
  508. HttpContext.Current.Response.Cookies[HttpContext.Current.Request.Cookies.Keys[i]].Values.Clear();
  509. }
  510. }
  511. /// <summary>
  512. /// 移除Cookies
  513. /// </summary>
  514. /// <param name="cookiesName"></param>
  515. public static void RemoveCookies(string cookiesName)
  516. {
  517. if (string.IsNullOrEmpty(cookiesName))
  518. return;
  519. HttpCookie cookies = HttpContext.Current.Request.Cookies[cookiesName];
  520. if (null != cookies)
  521. {
  522. //HttpContext.Current.Response.Cookies[cookiesName].Domain = ".8200.cn";
  523. HttpContext.Current.Response.Cookies[cookiesName].Expires = DateTime.Now.AddDays(-600);
  524. HttpContext.Current.Response.Cookies[cookiesName].Values.Clear();
  525. }
  526. }
  527. /// <summary>
  528. /// 将IP地址转为整数形式
  529. /// </summary>
  530. /// <returns>整数</returns>
  531. public static long IP2Long(IPAddress ip)
  532. {
  533. int x = 3;
  534. long o = 0;
  535. foreach (byte f in ip.GetAddressBytes())
  536. {
  537. o += (long)f << 8 * x--;
  538. }
  539. return o;
  540. }
  541. /// <summary>
  542. /// 将整数转为IP地址
  543. /// </summary>
  544. /// <returns>IP地址</returns>
  545. public static IPAddress Long2IP(long l)
  546. {
  547. byte[] b = new byte[4];
  548. for (int i = 0; i < 4; i++)
  549. {
  550. b[3 - i] = (byte)(l >> 8 * i & 255);
  551. }
  552. return new IPAddress(b);
  553. }
  554. /// <summary>
  555. /// 生成随机因子
  556. /// </summary>
  557. /// <returns></returns>
  558. static int GetRandomSeed()
  559. {
  560. byte[] bytes = new byte[4];
  561. System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
  562. rng.GetBytes(bytes);
  563. return BitConverter.ToInt32(bytes, 0);
  564. }
  565. /// <summary>
  566. /// 生成min-max的随机数
  567. /// </summary>
  568. /// <param name="min"></param>
  569. /// <param name="max"></param>
  570. /// <returns></returns>
  571. public static int GetRandomInt(int min, int max)
  572. {
  573. Random random = new Random(GetRandomSeed());
  574. return random.Next(min, max);
  575. }
  576. /// <summary>
  577. /// 生成4位数字随机数
  578. /// </summary>
  579. /// <returns></returns>
  580. public static string GetRandomInt()
  581. {
  582. Random random = new Random();
  583. return (random.Next(1000, 9999).ToString());
  584. }
  585. /// <summary>
  586. /// 去除List中重复的项
  587. /// </summary>
  588. /// <param name="list"></param>
  589. /// <returns></returns>
  590. public static List<string> getUnque(List<string> list)
  591. {
  592. List<string> list1 = new List<string>();
  593. Hashtable hash = new Hashtable();
  594. foreach (string stu in list)
  595. {
  596. if (!hash.ContainsKey(stu))
  597. {
  598. hash.Add(stu, stu);
  599. list1.Add(stu);
  600. }
  601. }
  602. hash.Clear();
  603. hash = null;
  604. return list1;
  605. }
  606. /// <summary>
  607. /// 返回字符串真实长度, 1个汉字长度为2
  608. /// </summary>
  609. /// <returns>字符长度</returns>
  610. public static int GetStringLength(string str)
  611. {
  612. return Encoding.Default.GetBytes(str).Length;
  613. }
  614. /// <summary>
  615. /// 判断指定字符串在指定字符串数组中的位置
  616. /// </summary>
  617. /// <param name="strSearch">字符串</param>
  618. /// <param name="stringArray">字符串数组</param>
  619. /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
  620. /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
  621. public static int GetInArrayID(string strSearch, string[] stringArray, bool caseInsensetive)
  622. {
  623. for (int i = 0; i < stringArray.Length; i++)
  624. {
  625. if (caseInsensetive)
  626. {
  627. if (strSearch.ToLower() == stringArray[i].ToLower())
  628. return i;
  629. }
  630. else if (strSearch == stringArray[i])
  631. return i;
  632. }
  633. return -1;
  634. }
  635. /// <summary>
  636. /// 判断指定字符串在指定字符串数组中的位置
  637. /// </summary>
  638. /// <param name="strSearch">字符串</param>
  639. /// <param name="stringArray">字符串数组</param>
  640. /// <returns>字符串在指定字符串数组中的位置, 如不存在则返回-1</returns>
  641. public static int GetInArrayID(string strSearch, string[] stringArray)
  642. {
  643. return GetInArrayID(strSearch, stringArray, true);
  644. }
  645. /// <summary>
  646. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  647. /// </summary>
  648. /// <param name="strSearch">字符串</param>
  649. /// <param name="stringArray">字符串数组</param>
  650. /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
  651. /// <returns>判断结果</returns>
  652. public static bool InArray(string strSearch, string[] stringArray, bool caseInsensetive)
  653. {
  654. return GetInArrayID(strSearch, stringArray, caseInsensetive) >= 0;
  655. }
  656. /// <summary>
  657. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  658. /// </summary>
  659. /// <param name="str">字符串</param>
  660. /// <param name="stringarray">字符串数组</param>
  661. /// <returns>判断结果</returns>
  662. public static bool InArray(string str, string[] stringarray)
  663. {
  664. return InArray(str, stringarray, false);
  665. }
  666. /// <summary>
  667. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  668. /// </summary>
  669. /// <param name="str">字符串</param>
  670. /// <param name="stringarray">内部以逗号分割单词的字符串</param>
  671. /// <returns>判断结果</returns>
  672. public static bool InArray(string str, string stringarray)
  673. {
  674. return InArray(str, SplitString(stringarray, ","), false);
  675. }
  676. /// <summary>
  677. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  678. /// </summary>
  679. /// <param name="str">字符串</param>
  680. /// <param name="stringarray">内部以逗号分割单词的字符串</param>
  681. /// <param name="strsplit">分割字符串</param>
  682. /// <returns>判断结果</returns>
  683. public static bool InArray(string str, string stringarray, string strsplit)
  684. {
  685. return InArray(str, SplitString(stringarray, strsplit), false);
  686. }
  687. /// <summary>
  688. /// 判断指定字符串是否属于指定字符串数组中的一个元素
  689. /// </summary>
  690. /// <param name="str">字符串</param>
  691. /// <param name="stringarray">内部以逗号分割单词的字符串</param>
  692. /// <param name="strsplit">分割字符串</param>
  693. /// <param name="caseInsensetive">是否不区分大小写, true为不区分, false为区分</param>
  694. /// <returns>判断结果</returns>
  695. public static bool InArray(string str, string stringarray, string strsplit, bool caseInsensetive)
  696. {
  697. return InArray(str, SplitString(stringarray, strsplit), caseInsensetive);
  698. }
  699. public static string CutString(string str, int length)
  700. {
  701. return CutString(str, 0, length);
  702. }
  703. /// <summary>
  704. /// 从字符串的指定位置开始截取到字符串结尾的了符串
  705. /// </summary>
  706. /// <param name="str">原字符串</param>
  707. /// <param name="startIndex">子字符串的起始位置</param>
  708. /// <returns>子字符串</returns>
  709. private static string CutString(string str, int startIndex, int length)
  710. {
  711. if (startIndex >= 0)
  712. {
  713. if (length < 0)
  714. {
  715. length = length * -1;
  716. if (startIndex - length < 0)
  717. {
  718. length = startIndex;
  719. startIndex = 0;
  720. }
  721. else
  722. {
  723. startIndex = startIndex - length;
  724. }
  725. }
  726. if (startIndex > str.Length)
  727. {
  728. return "";
  729. }
  730. }
  731. else
  732. {
  733. if (length < 0)
  734. {
  735. return "";
  736. }
  737. else
  738. {
  739. if (length + startIndex > 0)
  740. {
  741. length = length + startIndex;
  742. startIndex = 0;
  743. }
  744. else
  745. {
  746. return "";
  747. }
  748. }
  749. }
  750. if (str.Length - startIndex < length)
  751. {
  752. length = str.Length - startIndex;
  753. }
  754. return str.Substring(startIndex, length);
  755. }
  756. /// <summary>
  757. /// 获得当前绝对路径
  758. /// </summary>
  759. /// <param name="strPath">指定的路径</param>
  760. /// <returns>绝对路径</returns>
  761. public static string GetMapPath(string strPath)
  762. {
  763. if (HttpContext.Current != null)
  764. {
  765. return HttpContext.Current.Server.MapPath(strPath);
  766. }
  767. else
  768. {
  769. strPath = strPath.Replace("/", "\\");
  770. if (strPath.StartsWith("\\"))
  771. {
  772. strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
  773. }
  774. return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
  775. }
  776. }
  777. /// <summary>
  778. /// 返回文件是否存在
  779. /// </summary>
  780. /// <param name="filename">文件名</param>
  781. /// <returns>是否存在</returns>
  782. public static bool FileExists(string filename)
  783. {
  784. return System.IO.File.Exists(filename);
  785. }
  786. /// <summary>
  787. /// 以指定的ContentType输出指定文件文件
  788. /// </summary>
  789. /// <param name="filepath">文件路径</param>
  790. /// <param name="filename">输出的文件名</param>
  791. /// <param name="filetype">将文件输出时设置的ContentType</param>
  792. public static void ResponseFile(string filepath, string filename, string filetype)
  793. {
  794. Stream iStream = null;
  795. // 缓冲区为10k
  796. byte[] buffer = new Byte[10000];
  797. // 文件长度
  798. int length;
  799. // 需要读的数据长度
  800. long dataToRead;
  801. try
  802. {
  803. // 打开文件
  804. iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  805. // 需要读的数据长度
  806. dataToRead = iStream.Length;
  807. HttpContext.Current.Response.ContentType = filetype;
  808. if (HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].IndexOf("MSIE") > -1)
  809. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Utils.UrlEncode(filename.Trim()).Replace("+", " "));
  810. else
  811. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename.Trim());
  812. while (dataToRead > 0)
  813. {
  814. // 检查客户端是否还处于连接状态
  815. if (HttpContext.Current.Response.IsClientConnected)
  816. {
  817. length = iStream.Read(buffer, 0, 10000);
  818. HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
  819. HttpContext.Current.Response.Flush();
  820. buffer = new Byte[10000];
  821. dataToRead = dataToRead - length;
  822. }
  823. else
  824. {
  825. // 如果不再连接则跳出死循环
  826. dataToRead = -1;
  827. }
  828. }
  829. }
  830. catch (Exception ex)
  831. {
  832. HttpContext.Current.Response.Write("Error : " + ex.Message);
  833. }
  834. finally
  835. {
  836. if (iStream != null)
  837. {
  838. // 关闭文件
  839. iStream.Close();
  840. }
  841. }
  842. HttpContext.Current.Response.End();
  843. }
  844. /// <summary>
  845. /// int型转换为string型
  846. /// </summary>
  847. /// <returns>转换后的string类型结果</returns>
  848. public static string IntToStr(int intValue)
  849. {
  850. return Convert.ToString(intValue);
  851. }
  852. /// <summary>
  853. /// MD5函数
  854. /// 返回值为大写
  855. /// </summary>
  856. /// <param name="str">原始字符串</param>
  857. /// <returns>MD5结果</returns>
  858. public static string MD5(string str)
  859. {
  860. if (string.IsNullOrEmpty(str))
  861. return "";
  862. //加了码的md5
  863. str = "www." + str + ".8200.cn";
  864. byte[] b = Encoding.UTF8.GetBytes(str);
  865. b = new MD5CryptoServiceProvider().ComputeHash(b);
  866. string ret = "";
  867. for (int i = 0; i < b.Length; i++)
  868. ret += b[i].ToString("x").PadLeft(2, '0');
  869. return ret.ToUpper();
  870. }
  871. /// <summary>
  872. /// 通用MD5函数,未加码
  873. /// 返回值为大写
  874. /// </summary>
  875. /// <param name="str">原始字符串</param>
  876. /// <returns>MD5结果</returns>
  877. public static string GetMD5(string str)
  878. {
  879. if (string.IsNullOrEmpty(str))
  880. return "";
  881. byte[] b = Encoding.UTF8.GetBytes(str);
  882. b = new MD5CryptoServiceProvider().ComputeHash(b);
  883. string ret = "";
  884. for (int i = 0; i < b.Length; i++)
  885. ret += b[i].ToString("x").PadLeft(2, '0');
  886. return ret.ToUpper();
  887. }
  888. /// <summary>
  889. /// 字符串如果操过指定长度则将超出的部分用指定字符串代替
  890. /// </summary>
  891. /// <param name="p_SrcString">要检查的字符串</param>
  892. /// <param name="p_Length">指定长度</param>
  893. /// <param name="p_TailString">用于替换的字符串</param>
  894. /// <returns>截取后的字符串</returns>
  895. public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
  896. {
  897. return GetSubString(p_SrcString, 0, p_Length, p_TailString);
  898. }
  899. public static string GetUnicodeSubString(string str, int len, string p_TailString)
  900. {
  901. string result = string.Empty;// 最终返回的结果
  902. int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
  903. int charLen = str.Length;// 把字符平等对待时的字符串长度
  904. int byteCount = 0;// 记录读取进度
  905. int pos = 0;// 记录截取位置
  906. if (byteLen > len)
  907. {
  908. for (int i = 0; i < charLen; i++)
  909. {
  910. if (TypeConverter.ObjectToInt(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
  911. byteCount += 2;
  912. else// 按英文字符计算加1
  913. byteCount += 1;
  914. if (byteCount > len)// 超出时只记下上一个有效位置
  915. {
  916. pos = i;
  917. break;
  918. }
  919. else if (byteCount == len)// 记下当前位置
  920. {
  921. pos = i + 1;
  922. break;
  923. }
  924. }
  925. if (pos >= 0)
  926. result = str.Substring(0, pos) + p_TailString;
  927. }
  928. else
  929. result = str;
  930. return result;
  931. }
  932. /// <summary>
  933. /// 取指定长度的字符串
  934. /// </summary>
  935. /// <param name="p_SrcString">要检查的字符串</param>
  936. /// <param name="p_StartIndex">起始位置</param>
  937. /// <param name="p_Length">指定长度</param>
  938. /// <param name="p_TailString">用于替换的字符串</param>
  939. /// <returns>截取后的字符串</returns>
  940. public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
  941. {
  942. string myResult = p_SrcString;
  943. Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString);
  944. foreach (char c in Encoding.UTF8.GetChars(bComments))
  945. { //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
  946. if ((c > '\u0800' && c < '\u4e00') || (c > '\xAC00' && c < '\xD7A3'))
  947. {
  948. //if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+"))
  949. //当截取的起始位置超出字段串长度时
  950. if (p_StartIndex >= p_SrcString.Length)
  951. return "";
  952. else
  953. return p_SrcString.Substring(p_StartIndex,
  954. ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
  955. }
  956. }
  957. if (p_Length >= 0)
  958. {
  959. byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);
  960. //当字符串长度大于起始位置
  961. if (bsSrcString.Length > p_StartIndex)
  962. {
  963. int p_EndIndex = bsSrcString.Length;
  964. //当要截取的长度在字符串的有效长度范围内
  965. if (bsSrcString.Length > (p_StartIndex + p_Length))
  966. {
  967. p_EndIndex = p_Length + p_StartIndex;
  968. }
  969. else
  970. { //当不在有效范围内时,只取到字符串的结尾
  971. p_Length = bsSrcString.Length - p_StartIndex;
  972. p_TailString = "";
  973. }
  974. int nRealLength = p_Length;
  975. int[] anResultFlag = new int[p_Length];
  976. byte[] bsResult = null;
  977. int nFlag = 0;
  978. for (int i = p_StartIndex; i < p_EndIndex; i++)
  979. {
  980. if (bsSrcString[i] > 127)
  981. {
  982. nFlag++;
  983. if (nFlag == 3)
  984. nFlag = 1;
  985. }
  986. else
  987. nFlag = 0;
  988. anResultFlag[i] = nFlag;
  989. }
  990. if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
  991. nRealLength = p_Length + 1;
  992. bsResult = new byte[nRealLength];
  993. Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength);
  994. myResult = Encoding.Default.GetString(bsResult);
  995. myResult = myResult + p_TailString;
  996. }
  997. }
  998. return myResult;
  999. }
  1000. /// <summary>
  1001. /// 自定义的替换字符串函数
  1002. /// </summary>
  1003. public static string ReplaceString(string SourceString, string SearchString, string ReplaceString, bool IsCaseInsensetive)
  1004. {
  1005. return Regex.Replace(SourceString, Regex.Escape(SearchString), ReplaceString, IsCaseInsensetive ? RegexOptions.IgnoreCase : RegexOptions.None);
  1006. }
  1007. /// <summary>
  1008. /// 检测是否是正确的Url
  1009. /// </summary>
  1010. /// <param name="strUrl">要验证的Url</param>
  1011. /// <returns>判断结果</returns>
  1012. public static bool IsURL(string strUrl)
  1013. {
  1014. 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\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
  1015. }
  1016. /// <summary>
  1017. /// 检测是否有Sql危险字符
  1018. /// </summary>
  1019. /// <param name="str">要判断字符串</param>
  1020. /// <returns>判断结果</returns>
  1021. public static bool IsSafeSqlString(string str)
  1022. {
  1023. return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
  1024. }
  1025. /// <summary>
  1026. /// 检测是否有危险的可能用于链接的字符串
  1027. /// </summary>
  1028. /// <param name="str">要判断字符串</param>
  1029. /// <returns>判断结果</returns>
  1030. public static bool IsSafeUserInfoString(string str)
  1031. {
  1032. return !Regex.IsMatch(str, @"^\s*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^Guest|管理员|彩站|彩宝|8200");
  1033. }
  1034. /// <summary>
  1035. /// 清理字符串
  1036. /// </summary>
  1037. public static string CleanInput(string strIn)
  1038. {
  1039. return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
  1040. }
  1041. /// <summary>
  1042. /// 返回URL中结尾的文件名
  1043. /// </summary>
  1044. public static string GetFilename(string url)
  1045. {
  1046. if (url == null)
  1047. {
  1048. return "";
  1049. }
  1050. string[] strs1 = url.Split(new char[] { '/' });
  1051. return strs1[strs1.Length - 1].Split(new char[] { '?' })[0];
  1052. }
  1053. /// <summary>
  1054. /// 判断字符串是否为时间
  1055. /// </summary>
  1056. /// <returns></returns>
  1057. public static bool IsTime(string timeval)
  1058. {
  1059. return Regex.IsMatch(timeval, @"^((([0-1]?[0-9])|(2[0-3])):([0-5]?[0-9])(:[0-5]?[0-9])?)$");
  1060. }
  1061. /// <summary>
  1062. /// 改正sql语句中的转义字符
  1063. /// </summary>
  1064. public static string mashSQL(string str)
  1065. {
  1066. return (str == null) ? "" : str.Replace("\'", "'");
  1067. }
  1068. /// <summary>
  1069. /// 替换sql语句中的有问题符号
  1070. /// </summary>
  1071. public static string ChkSQL(string str)
  1072. {
  1073. return (str == null) ? "" : str.Replace("'", "''");
  1074. }
  1075. /// <summary>
  1076. /// 转换为静态html
  1077. /// </summary>
  1078. public void transHtml(string path, string outpath)
  1079. {
  1080. Page page = new Page();
  1081. StringWriter writer = new StringWriter();
  1082. page.Server.Execute(path, writer);
  1083. FileStream fs;
  1084. if (File.Exists(page.Server.MapPath("") + "\\" + outpath))
  1085. {
  1086. File.Delete(page.Server.MapPath("") + "\\" + outpath);
  1087. fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
  1088. }
  1089. else
  1090. {
  1091. fs = File.Create(page.Server.MapPath("") + "\\" + outpath);
  1092. }
  1093. byte[] bt = Encoding.Default.GetBytes(writer.ToString());
  1094. fs.Write(bt, 0, bt.Length);
  1095. fs.Close();
  1096. }
  1097. /// <summary>
  1098. /// 分割字符串
  1099. /// </summary>
  1100. public static string[] SplitString(string strContent, string strSplit)
  1101. {
  1102. if (!String.IsNullOrEmpty(strContent))
  1103. {
  1104. if (strContent.IndexOf(strSplit) < 0)
  1105. return new string[] { strContent };
  1106. return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);
  1107. }
  1108. else
  1109. return new string[0] { };
  1110. }
  1111. /// <summary>
  1112. /// 分割字符串
  1113. /// </summary>
  1114. /// <returns></returns>
  1115. public static string[] SplitString(string strContent, string strSplit, int count)
  1116. {
  1117. string[] result = new string[count];
  1118. string[] splited = SplitString(strContent, strSplit);
  1119. for (int i = 0; i < count; i++)
  1120. {
  1121. if (i < splited.Length)
  1122. result[i] = splited[i];
  1123. else
  1124. result[i] = string.Empty;
  1125. }
  1126. return result;
  1127. }
  1128. /// <summary>
  1129. /// 过滤字符串数组中每个元素为合适的大小
  1130. /// 当长度小于minLength时,忽略掉,-1为不限制最小长度
  1131. /// 当长度大于maxLength时,取其前maxLength位
  1132. /// 如果数组中有null元素,会被忽略掉
  1133. /// </summary>
  1134. /// <param name="minLength">单个元素最小长度</param>
  1135. /// <param name="maxLength">单个元素最大长度</param>
  1136. /// <returns></returns>
  1137. public static string[] PadStringArray(string[] strArray, int minLength, int maxLength)
  1138. {
  1139. if (minLength > maxLength)
  1140. {
  1141. int t = maxLength;
  1142. maxLength = minLength;
  1143. minLength = t;
  1144. }
  1145. int iMiniStringCount = 0;
  1146. for (int i = 0; i < strArray.Length; i++)
  1147. {
  1148. if (minLength > -1 && strArray[i].Length < minLength)
  1149. {
  1150. strArray[i] = null;
  1151. continue;
  1152. }
  1153. if (strArray[i].Length > maxLength)
  1154. strArray[i] = strArray[i].Substring(0, maxLength);
  1155. iMiniStringCount++;
  1156. }
  1157. string[] result = new string[iMiniStringCount];
  1158. for (int i = 0, j = 0; i < strArray.Length && j < result.Length; i++)
  1159. {
  1160. if (strArray[i] != null && strArray[i] != string.Empty)
  1161. {
  1162. result[j] = strArray[i];
  1163. j++;
  1164. }
  1165. }
  1166. return result;
  1167. }
  1168. /// <summary>
  1169. /// 分割字符串
  1170. /// </summary>
  1171. /// <param name="strContent">被分割的字符串</param>
  1172. /// <param name="strSplit">分割符</param>
  1173. /// <param name="ignoreRepeatItem">忽略重复项</param>
  1174. /// <param name="maxElementLength">单个元素最大长度</param>
  1175. /// <returns></returns>
  1176. public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem, int maxElementLength)
  1177. {
  1178. string[] result = SplitString(strContent, strSplit);
  1179. return ignoreRepeatItem ? DistinctStringArray(result, maxElementLength) : result;
  1180. }
  1181. public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem, int minElementLength, int maxElementLength)
  1182. {
  1183. string[] result = SplitString(strContent, strSplit);
  1184. if (ignoreRepeatItem)
  1185. {
  1186. result = DistinctStringArray(result);
  1187. }
  1188. return PadStringArray(result, minElementLength, maxElementLength);
  1189. }
  1190. /// <summary>
  1191. /// 分割字符串
  1192. /// </summary>
  1193. /// <param name="strContent">被分割的字符串</param>
  1194. /// <param name="strSplit">分割符</param>
  1195. /// <param name="ignoreRepeatItem">忽略重复项</param>
  1196. /// <returns></returns>
  1197. public static string[] SplitString(string strContent, string strSplit, bool ignoreRepeatItem)
  1198. {
  1199. return SplitString(strContent, strSplit, ignoreRepeatItem, 0);
  1200. }
  1201. /// <summary>
  1202. /// 清除字符串数组中的重复项
  1203. /// </summary>
  1204. /// <param name="strArray">字符串数组</param>
  1205. /// <param name="maxElementLength">字符串数组中单个元素的最大长度</param>
  1206. /// <returns></returns>
  1207. public static string[] DistinctStringArray(string[] strArray, int maxElementLength)
  1208. {
  1209. Hashtable h = new Hashtable();
  1210. foreach (string s in strArray)
  1211. {
  1212. string k = s;
  1213. if (maxElementLength > 0 && k.Length > maxElementLength)
  1214. {
  1215. k = k.Substring(0, maxElementLength);
  1216. }
  1217. h[k.Trim()] = s;
  1218. }
  1219. string[] result = new string[h.Count];
  1220. h.Keys.CopyTo(result, 0);
  1221. return result;
  1222. }
  1223. /// <summary>
  1224. /// 清除字符串数组中的重复项
  1225. /// </summary>
  1226. /// <param name="strArray">字符串数组</param>
  1227. /// <returns></returns>
  1228. public static string[] DistinctStringArray(string[] strArray)
  1229. {
  1230. return DistinctStringArray(strArray, 0);
  1231. }
  1232. /// <summary>
  1233. /// 替换html字符
  1234. /// </summary>
  1235. public static string EncodeHtml(string strHtml)
  1236. {
  1237. if (strHtml != "")
  1238. {
  1239. strHtml = strHtml.Replace(",", "&def");
  1240. strHtml = strHtml.Replace("'", "&dot");
  1241. strHtml = strHtml.Replace(";", "&dec");
  1242. return strHtml;
  1243. }
  1244. return "";
  1245. }
  1246. /// <summary>
  1247. /// 进行指定的替换(脏字过滤)
  1248. /// </summary>
  1249. public static string StrFilter(string str, string bantext)
  1250. {
  1251. string text1 = "", text2 = "";
  1252. string[] textArray1 = SplitString(bantext, "\r\n");
  1253. for (int num1 = 0; num1 < textArray1.Length; num1++)
  1254. {
  1255. text1 = textArray1[num1].Substring(0, textArray1[num1].IndexOf("="));
  1256. text2 = textArray1[num1].Substring(textArray1[num1].IndexOf("=") + 1);
  1257. str = str.Replace(text1, text2);
  1258. }
  1259. return str;
  1260. }
  1261. /// <summary>
  1262. /// 返回 HTML 字符串的编码结果
  1263. /// </summary>
  1264. /// <param name="str">字符串</param>
  1265. /// <returns>编码结果</returns>
  1266. public static string HtmlEncode(string str)
  1267. {
  1268. return HttpUtility.HtmlEncode(str);
  1269. }
  1270. /// <summary>
  1271. /// 返回 HTML 字符串的解码结果
  1272. /// </summary>
  1273. /// <param name="str">字符串</param>
  1274. /// <returns>解码结果</returns>
  1275. public static string HtmlDecode(string str)
  1276. {
  1277. return HttpUtility.HtmlDecode(str);
  1278. }
  1279. /// <summary>
  1280. /// 返回 URL 字符串的编码结果
  1281. /// </summary>
  1282. /// <param name="str">字符串</param>
  1283. /// <returns>编码结果</returns>
  1284. public static string UrlEncode(string str)
  1285. {
  1286. return HttpUtility.UrlEncode(str);
  1287. }
  1288. /// <summary>
  1289. /// 返回 URL 字符串的编码结果
  1290. /// </summary>
  1291. /// <param name="str">字符串</param>
  1292. /// <returns>解码结果</returns>
  1293. public static string UrlDecode(string str)
  1294. {
  1295. return HttpUtility.UrlDecode(str);
  1296. }
  1297. /// <summary>
  1298. /// 返回指定目录下的非 UTF8 字符集文件
  1299. /// </summary>
  1300. /// <param name="Path">路径</param>
  1301. /// <returns>文件名的字符串数组</returns>
  1302. public static string[] FindNoUTF8File(string Path)
  1303. {
  1304. StringBuilder filelist = new StringBuilder();
  1305. DirectoryInfo Folder = new DirectoryInfo(Path);
  1306. FileInfo[] subFiles = Folder.GetFiles();
  1307. for (int j = 0; j < subFiles.Length; j++)
  1308. {
  1309. if (subFiles[j].Extension.ToLower().Equals(".htm"))
  1310. {
  1311. FileStream fs = new FileStream(subFiles[j].FullName, FileMode.Open, FileAccess.Read);
  1312. bool bUtf8 = IsUTF8(fs);
  1313. fs.Close();
  1314. if (!bUtf8)
  1315. {
  1316. filelist.Append(subFiles[j].FullName);
  1317. filelist.Append("\r\n");
  1318. }
  1319. }
  1320. }
  1321. return Utils.SplitString(filelist.ToString(), "\r\n");
  1322. }
  1323. //0000 0000-0000 007F - 0xxxxxxx (ascii converts to 1 octet!)
  1324. //0000 0080-0000 07FF - 110xxxxx 10xxxxxx ( 2 octet format)
  1325. //0000 0800-0000 FFFF - 1110xxxx 10xxxxxx 10xxxxxx (3 octet format)
  1326. /// <summary>
  1327. /// 判断文件流是否为UTF8字符集
  1328. /// </summary>
  1329. /// <param name="sbInputStream">文件流</param>
  1330. /// <returns>判断结果</returns>
  1331. private static bool IsUTF8(FileStream sbInputStream)
  1332. {
  1333. int i;
  1334. byte cOctets; // octets to go in this UTF-8 encoded character
  1335. byte chr;
  1336. bool bAllAscii = true;
  1337. long iLen = sbInputStream.Length;
  1338. cOctets = 0;
  1339. for (i = 0; i < iLen; i++)
  1340. {
  1341. chr = (byte)sbInputStream.ReadByte();
  1342. if ((chr & 0x80) != 0) bAllAscii = false;
  1343. if (cOctets == 0)
  1344. {
  1345. if (chr >= 0x80)
  1346. {
  1347. do
  1348. {
  1349. chr <<= 1;
  1350. cOctets++;
  1351. }
  1352. while ((chr & 0x80) != 0);
  1353. cOctets--;
  1354. if (cOctets == 0)
  1355. return false;
  1356. }
  1357. }
  1358. else
  1359. {
  1360. if ((chr & 0xC0) != 0x80)
  1361. return false;
  1362. cOctets--;
  1363. }
  1364. }
  1365. if (cOctets > 0)
  1366. return false;
  1367. if (bAllAscii)
  1368. return false;
  1369. return true;
  1370. }
  1371. /// <summary>
  1372. /// 是否为ip
  1373. /// </summary>
  1374. /// <param name="ip"></param>
  1375. /// <returns></returns>
  1376. public static bool IsIP(string ip)
  1377. {
  1378. 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?)$");
  1379. }
  1380. public static bool IsIPSect(string ip)
  1381. {
  1382. 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?|\*)$");
  1383. }
  1384. /// <summary>
  1385. /// 将全角数字转换为数字
  1386. /// </summary>
  1387. /// <param name="SBCCase"></param>
  1388. /// <returns></returns>
  1389. public static string SBCCaseToNumberic(string SBCCase)
  1390. {
  1391. char[] c = SBCCase.ToCharArray();
  1392. for (int i = 0; i < c.Length; i++)
  1393. {
  1394. byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
  1395. if (b.Length == 2)
  1396. {
  1397. if (b[1] == 255)
  1398. {
  1399. b[0] = (byte)(b[0] + 32);
  1400. b[1] = 0;
  1401. c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
  1402. }
  1403. }
  1404. }
  1405. return new string(c);
  1406. }
  1407. /// <summary>
  1408. /// 移除Html标记
  1409. /// </summary>
  1410. /// <param name="content"></param>
  1411. /// <returns></returns>
  1412. public static string RemoveHtml(string content)
  1413. {
  1414. return Regex.Replace(content, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);
  1415. }
  1416. /// <summary>
  1417. /// 过滤HTML中的不安全标签
  1418. /// </summary>
  1419. /// <param name="content"></param>
  1420. /// <returns></returns>
  1421. public static string RemoveUnsafeHtml(string content)
  1422. {
  1423. content = Regex.Replace(content, @"(\<|\s+)o([a-z]+\s?=)", "$1$2", RegexOptions.IgnoreCase);
  1424. content = Regex.Replace(content, @"(script|frame|form|meta|behavior|style)([\s|:|>])+", "$1.$2", RegexOptions.IgnoreCase);
  1425. return content;
  1426. }
  1427. /// <summary>
  1428. /// object型转换为bool型
  1429. /// </summary>
  1430. /// <param name="strValue">要转换的字符串</param>
  1431. /// <param name="defValue">缺省值</param>
  1432. /// <returns>转换后的bool类型结果</returns>
  1433. public static bool StrToBool(object expression, bool defValue)
  1434. {
  1435. return TypeConverter.StrToBool(expression, defValue);
  1436. }
  1437. /// <summary>
  1438. /// string型转换为bool型
  1439. /// </summary>
  1440. /// <param name="strValue">要转换的字符串</param>
  1441. /// <param name="defValue">缺省值</param>
  1442. /// <returns>转换后的bool类型结果</returns>
  1443. public static bool StrToBool(string expression, bool defValue)
  1444. {
  1445. return TypeConverter.StrToBool(expression, defValue);
  1446. }
  1447. /// <summary>
  1448. /// 将对象转换为Int32类型
  1449. /// </summary>
  1450. /// <param name="expression">要转换的字符串</param>
  1451. /// <param name="defValue">缺省值</param>
  1452. /// <returns>转换后的int类型结果</returns>
  1453. public static int StrToInt(object expression, int defValue)
  1454. {
  1455. return TypeConverter.ObjectToInt(expression, defValue);
  1456. }
  1457. /// <summary>
  1458. /// 将字符串转换为Int32类型
  1459. /// </summary>
  1460. /// <param name="expression">要转换的字符串</param>
  1461. /// <param name="defValue">缺省值</param>
  1462. /// <returns>转换后的int类型结果</returns>
  1463. public static int StrToInt(string expression, int defValue)
  1464. {
  1465. return TypeConverter.StrToInt(expression, defValue);
  1466. }
  1467. /// <summary>
  1468. /// Object型转换为float型
  1469. /// </summary>
  1470. /// <param name="strValue">要转换的字符串</param>
  1471. /// <param name="defValue">缺省值</param>
  1472. /// <returns>转换后的int类型结果</returns>
  1473. public static float StrToFloat(object strValue, float defValue)
  1474. {
  1475. return TypeConverter.StrToFloat(strValue, defValue);
  1476. }
  1477. /// <summary>
  1478. /// string型转换为float型
  1479. /// </summary>
  1480. /// <param name="strValue">要转换的字符串</param>
  1481. /// <param name="defValue">缺省值</param>
  1482. /// <returns>转换后的int类型结果</returns>
  1483. public static float StrToFloat(string strValue, float defValue)
  1484. {
  1485. return TypeConverter.StrToFloat(strValue, defValue);
  1486. }
  1487. /// <summary>
  1488. /// 验证是否为正整数
  1489. /// </summary>
  1490. /// <param name="str"></param>
  1491. /// <returns></returns>
  1492. public static bool IsInt(string str)
  1493. {
  1494. return Regex.IsMatch(str, @"^[0-9]*$");
  1495. }
  1496. /// <summary>
  1497. /// 根据Url获得源文件内容
  1498. /// </summary>
  1499. /// <param name="url">合法的Url地址</param>
  1500. /// <returns></returns>
  1501. public static string GetSourceTextByUrl(string url)
  1502. {
  1503. try
  1504. {
  1505. WebRequest request = WebRequest.Create(url);
  1506. request.Timeout = 20000;//20秒超时
  1507. WebResponse response = request.GetResponse();
  1508. Stream resStream = response.GetResponseStream();
  1509. StreamReader sr = new StreamReader(resStream);
  1510. return sr.ReadToEnd();
  1511. }
  1512. catch { return ""; }
  1513. }
  1514. /// <summary>
  1515. /// 合并字符
  1516. /// </summary>
  1517. /// <param name="source">要合并的源字符串</param>
  1518. /// <param name="target">要被合并到的目的字符串</param>
  1519. /// <param name="mergechar">合并符</param>
  1520. /// <returns>合并到的目的字符串</returns>
  1521. public static string MergeString(string source, string target)
  1522. {
  1523. return MergeString(source, target, ",");
  1524. }
  1525. /// <summary>
  1526. /// 合并字符
  1527. /// </summary>
  1528. /// <param name="source">要合并的源字符串</param>
  1529. /// <param name="target">要被合并到的目的字符串</param>
  1530. /// <param name="mergechar">合并符</param>
  1531. /// <returns>并到字符串</returns>
  1532. public static string MergeString(string source, string target, string mergechar)
  1533. {
  1534. if (String.IsNullOrEmpty(target))
  1535. target = source;
  1536. else
  1537. target += mergechar + source;
  1538. return target;
  1539. }
  1540. /// <summary>
  1541. /// 清除UBB标签
  1542. /// </summary>
  1543. /// <param name="sDetail">帖子内容</param>
  1544. /// <returns>帖子内容</returns>
  1545. public static string ClearUBB(string sDetail)
  1546. {
  1547. return Regex.Replace(sDetail, @"\[[^\]]*?\]", string.Empty, RegexOptions.IgnoreCase);
  1548. }
  1549. /// <summary>
  1550. /// 获取站点根目录URL
  1551. /// </summary>
  1552. /// <returns></returns>
  1553. public static string GetRootUrl(string forumPath)
  1554. {
  1555. int port = HttpContext.Current.Request.Url.Port;
  1556. return string.Format("{0}://{1}{2}{3}",
  1557. HttpContext.Current.Request.Url.Scheme,
  1558. HttpContext.Current.Request.Url.Host.ToString(),
  1559. (port == 80 || port == 0) ? "" : ":" + port,
  1560. forumPath);
  1561. }
  1562. /// <summary>
  1563. /// 获取指定文件的扩展名
  1564. /// </summary>
  1565. /// <param name="fileName">指定文件名</param>
  1566. /// <returns>扩展名</returns>
  1567. public static string GetFileExtName(string fileName)
  1568. {
  1569. if (String.IsNullOrEmpty(fileName) || fileName.IndexOf('.') <= 0)
  1570. return "";
  1571. fileName = fileName.ToLower().Trim();
  1572. return fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));
  1573. }
  1574. /// <summary>
  1575. /// http POST请求url
  1576. /// </summary>
  1577. /// <param name="url"></param>
  1578. /// <returns></returns>
  1579. public static string GetHttpWebResponse(string url)
  1580. {
  1581. return GetHttpWebResponse(url, string.Empty);
  1582. }
  1583. /// <summary>
  1584. /// http POST请求url
  1585. /// </summary>
  1586. /// <param name="apiUrl"></param>
  1587. /// <param name="method_name"></param>
  1588. /// <param name="postData"></param>
  1589. /// <returns></returns>
  1590. public static string GetHttpWebResponse(string url, string postData)
  1591. {
  1592. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  1593. request.Method = "POST";
  1594. request.ContentType = "application/x-www-form-urlencoded";
  1595. request.ContentLength = postData.Length;
  1596. request.Timeout = 20000;
  1597. HttpWebResponse response = null;
  1598. try
  1599. {
  1600. StreamWriter swRequestWriter = new StreamWriter(request.GetRequestStream());
  1601. swRequestWriter.Write(postData);
  1602. if (swRequestWriter != null)
  1603. swRequestWriter.Close();
  1604. response = (HttpWebResponse)request.GetResponse();
  1605. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  1606. {
  1607. return reader.ReadToEnd();
  1608. }
  1609. }
  1610. finally
  1611. {
  1612. if (response != null)
  1613. response.Close();
  1614. }
  1615. }
  1616. #region Private Methods
  1617. private static string[] browerNames = { "MSIE", "Firefox", "Opera", "Netscape", "Safari", "Lynx", "Konqueror", "Mozilla" };
  1618. //private const string[] osNames = { "Win", "Mac", "Linux", "FreeBSD", "SunOS", "OS/2", "AIX", "Bot", "Crawl", "Spider" };
  1619. /// <summary>
  1620. /// 获得浏览器信息
  1621. /// </summary>
  1622. /// <returns></returns>
  1623. public static string GetClientBrower()
  1624. {
  1625. string agent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
  1626. if (!string.IsNullOrEmpty(agent))
  1627. {
  1628. foreach (string name in browerNames)
  1629. {
  1630. if (agent.Contains(name))
  1631. return name;
  1632. }
  1633. }
  1634. return "Other";
  1635. }
  1636. /// <summary>
  1637. /// 获得操作系统信息
  1638. /// </summary>
  1639. /// <returns></returns>
  1640. public static string GetClientOS()
  1641. {
  1642. string os = string.Empty;
  1643. string agent = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
  1644. if (agent == null)
  1645. return "Other";
  1646. if (agent.IndexOf("Win") > -1)
  1647. os = "Windows";
  1648. else if (agent.IndexOf("Mac") > -1)
  1649. os = "Mac";
  1650. else if (agent.IndexOf("Linux") > -1)
  1651. os = "Linux";
  1652. else if (agent.IndexOf("FreeBSD") > -1)
  1653. os = "FreeBSD";
  1654. else if (agent.IndexOf("SunOS") > -1)
  1655. os = "SunOS";
  1656. else if (agent.IndexOf("OS/2") > -1)
  1657. os = "OS/2";
  1658. else if (agent.IndexOf("AIX") > -1)
  1659. os = "AIX";
  1660. else if (System.Text.RegularExpressions.Regex.IsMatch(agent, @"(Bot|Crawl|Spider)"))
  1661. os = "Spiders";
  1662. else
  1663. os = "Other";
  1664. return os;
  1665. }
  1666. #endregion
  1667. }
  1668. }