Function.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. using System;
  2. using System.Data;
  3. using System.Web;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. using System.Net.Mail;
  10. using System.Net;
  11. using LitJson;
  12. using Microsoft.AspNetCore.Http;
  13. using ThoughtWorks.QRCode.Codec;
  14. using System.Linq;
  15. using System.IO;
  16. namespace Common
  17. {
  18. public class Function
  19. {
  20. /// <summary>
  21. /// hmacSha1算法加密(生成长度40)
  22. /// </summary>
  23. /// <param name="encryptText">加密明文</param>
  24. /// <param name="encryptKey">加密密钥</param>
  25. /// <returns></returns>
  26. public static string hmacSha1(string encryptText, string encryptKey)
  27. {
  28. HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(encryptKey));
  29. byte[] RstRes = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(encryptText));
  30. StringBuilder EnText = new StringBuilder();
  31. foreach (byte Byte in RstRes)
  32. {
  33. EnText.AppendFormat("{0:x2}", Byte);
  34. }
  35. return EnText.ToString();
  36. }
  37. public static string hmacmd5(string encryptText, string encryptKey)
  38. {
  39. HMACMD5 myHMACSHA1 = new HMACMD5(Encoding.UTF8.GetBytes(encryptKey));
  40. byte[] RstRes = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(encryptText));
  41. StringBuilder EnText = new StringBuilder();
  42. foreach (byte Byte in RstRes)
  43. {
  44. EnText.AppendFormat("{0:x2}", Byte);
  45. }
  46. return EnText.ToString();
  47. }
  48. /// <summary>
  49. /// MD5 32位加密字符串
  50. /// </summary>
  51. /// <param name="str"></param>
  52. /// <returns></returns>
  53. public static string MD5_32(string str)
  54. {
  55. string cl = str + "@$1212#";
  56. string pwd = "";
  57. MD5 md5 = MD5.Create();//实例化一个md5对像
  58. // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
  59. byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
  60. // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
  61. for (int i = 0; i < s.Length; i++)
  62. {
  63. // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
  64. pwd = pwd + s[i].ToString("X").ToLower().PadLeft(2, '0');
  65. }
  66. return pwd;
  67. }
  68. public static string MD532(string str)
  69. {
  70. string cl = str;
  71. string pwd = "";
  72. MD5 md5 = MD5.Create();//实例化一个md5对像
  73. // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
  74. byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
  75. // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
  76. for (int i = 0; i < s.Length; i++)
  77. {
  78. // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
  79. pwd = pwd + s[i].ToString("X").ToLower().PadLeft(2, '0');
  80. }
  81. return pwd;
  82. }
  83. /// <summary>
  84. /// 获取MD5值
  85. /// </summary>
  86. /// <param name="str">加密的字符串</param>
  87. /// <returns>返回MD5值</returns>
  88. public static string MD5_16(string str)
  89. {
  90. return MD5_32(str).Substring(8, 16);
  91. }
  92. /// <summary>
  93. /// 写日志(错误报告)
  94. /// </summary>
  95. /// <param name="str"></param>
  96. public static void WriteLog(string str)
  97. {
  98. try
  99. {
  100. string path = getPath("/log/message/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/");
  101. if (!Directory.Exists(path))
  102. {
  103. Directory.CreateDirectory(path);
  104. }
  105. StreamWriter sw = File.AppendText(path + "content.log");
  106. sw.WriteLine(str);
  107. sw.Flush();
  108. sw.Dispose();
  109. }
  110. catch
  111. { }
  112. }
  113. /// <summary>
  114. /// 写日志(错误报告)
  115. /// </summary>
  116. /// <param name="str"></param>
  117. public static void WriteLog(string str, string filename)
  118. {
  119. try
  120. {
  121. string path = getPath("/log/" + filename + "/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/");
  122. if (!Directory.Exists(path))
  123. {
  124. Directory.CreateDirectory(path);
  125. }
  126. StreamWriter sw = File.AppendText(path + "content.log");
  127. sw.WriteLine(str);
  128. sw.Flush();
  129. sw.Dispose();
  130. }
  131. catch
  132. { }
  133. }
  134. public static void WriteLog(string path_str, string file_name, string page_content)
  135. {
  136. try
  137. {
  138. string path = getPath(path_str);
  139. if (!Directory.Exists(path))
  140. {
  141. Directory.CreateDirectory(path);
  142. }
  143. StreamWriter sw = File.AppendText(path + "/" + file_name);
  144. sw.WriteLine(page_content);
  145. sw.Flush();
  146. sw.Dispose();
  147. }
  148. catch
  149. { }
  150. }
  151. /// <summary>
  152. /// 过滤html代码
  153. /// </summary>
  154. /// <param name="Htmlstring"></param>
  155. public static string NoHTML(string Htmlstring) //去除HTML标记
  156. {
  157. if (Htmlstring == null || Htmlstring == string.Empty)
  158. {
  159. return "";
  160. }
  161. Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
  162. Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
  163. //Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
  164. Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
  165. Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
  166. Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
  167. Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
  168. Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
  169. Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
  170. Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
  171. Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
  172. Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
  173. Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
  174. Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
  175. Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
  176. Htmlstring = Regex.Replace(Htmlstring, @"&.*?;", "", RegexOptions.IgnoreCase);
  177. Htmlstring = Htmlstring.Replace("<", "〈");
  178. Htmlstring = Htmlstring.Replace(">", "〉");
  179. //Htmlstring = Htmlstring.Replace("\r\n", "");
  180. //Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
  181. return Htmlstring;
  182. }
  183. public static bool IsIncludeChinese(string str)
  184. {
  185. Regex r = new Regex(@"[\u4E00-\u9FA5]", RegexOptions.IgnoreCase);
  186. if (r.IsMatch(str))
  187. {
  188. return true;
  189. }
  190. else
  191. {
  192. return false;
  193. }
  194. }
  195. public static bool IsInt(string numberString)
  196. {
  197. if (string.IsNullOrEmpty(numberString))
  198. {
  199. return false;
  200. }
  201. Regex rCode = new Regex("^\\d+$");
  202. if (!rCode.IsMatch(numberString))
  203. {
  204. return false;
  205. }
  206. else
  207. {
  208. return true;
  209. }
  210. }
  211. public static string CheckInt(string numberString)
  212. {
  213. if (string.IsNullOrEmpty(numberString))
  214. {
  215. return "0";
  216. }
  217. Regex rCode = new Regex("^\\d+$");
  218. if (!rCode.IsMatch(numberString))
  219. {
  220. return "0";
  221. }
  222. else
  223. {
  224. return numberString;
  225. }
  226. }
  227. public static DateTime CheckDateTime(string numberString)
  228. {
  229. if (string.IsNullOrEmpty(numberString))
  230. {
  231. return DateTime.Now;
  232. }
  233. DateTime result;
  234. if (DateTime.TryParse(numberString, out result))
  235. {
  236. return result;
  237. }
  238. else
  239. {
  240. return DateTime.Now;
  241. }
  242. }
  243. public static bool ChkDateTime(string numberString)
  244. {
  245. if (string.IsNullOrEmpty(numberString))
  246. {
  247. return false;
  248. }
  249. DateTime result;
  250. if (DateTime.TryParse(numberString, out result))
  251. {
  252. return true;
  253. }
  254. else
  255. {
  256. return false;
  257. }
  258. }
  259. public static string CheckNull(string numberString)
  260. {
  261. if (string.IsNullOrEmpty(numberString))
  262. {
  263. return "";
  264. }
  265. else
  266. {
  267. return numberString;
  268. }
  269. }
  270. public static string CheckUrl(string str)
  271. {
  272. if (str == null || str == string.Empty)
  273. {
  274. return "";
  275. }
  276. Regex rCode = new Regex(@"((http|ftp|https)://)(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\&%_\./-~-]*)?");
  277. if (!rCode.IsMatch(str))
  278. {
  279. return "";
  280. }
  281. else
  282. {
  283. return str;
  284. }
  285. }
  286. public static string CheckEmail(string str)
  287. {
  288. if (str == null || str == string.Empty)
  289. {
  290. return "";
  291. }
  292. Regex rCode = new Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
  293. if (!rCode.IsMatch(str))
  294. {
  295. return "";
  296. }
  297. else
  298. {
  299. return str;
  300. }
  301. }
  302. public static string CheckMobile(string str)
  303. {
  304. if (str == null || str == string.Empty)
  305. {
  306. return "";
  307. }
  308. Regex rCode = new Regex(@"^1[3456789]\d{9}$");
  309. if (!rCode.IsMatch(str))
  310. {
  311. return "";
  312. }
  313. else
  314. {
  315. return str;
  316. }
  317. }
  318. public static string CheckIdCard(string str)
  319. {
  320. if (str == null || str == string.Empty)
  321. {
  322. return "";
  323. }
  324. Regex rCode = new Regex(@"^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$");
  325. if (!rCode.IsMatch(str))
  326. {
  327. return "";
  328. }
  329. else
  330. {
  331. return str;
  332. }
  333. }
  334. public static bool IsNum(string numberString)
  335. {
  336. if (string.IsNullOrEmpty(numberString))
  337. {
  338. return false;
  339. }
  340. Regex rCode = new Regex(@"^\d+(\.\d+)?$");
  341. if (!rCode.IsMatch(numberString))
  342. {
  343. return false;
  344. }
  345. else
  346. {
  347. return true;
  348. }
  349. }
  350. public static string CheckNum(string numberString)
  351. {
  352. if (string.IsNullOrEmpty(numberString))
  353. {
  354. return "0";
  355. }
  356. Regex rCode = new Regex(@"^\d+(\.\d+)?$");
  357. if (!rCode.IsMatch(numberString))
  358. {
  359. return "0";
  360. }
  361. else
  362. {
  363. return numberString;
  364. }
  365. }
  366. public static string CheckString(string str)
  367. {
  368. if (string.IsNullOrEmpty(str))
  369. {
  370. return "";
  371. }
  372. str = str.Replace("'", "&acute;");
  373. str = str.Replace("\"", "&quot;");
  374. //str = str.Replace(" ", "&nbsp;");
  375. str = str.Replace("<", "&lt;");
  376. str = str.Replace(">", "&gt;");
  377. str = str.Replace("(", "(");
  378. str = str.Replace(")", ")");
  379. str = ToDBC(str);
  380. return str;
  381. }
  382. public static string unCheckString(string str)
  383. {
  384. if (str == null || str == string.Empty)
  385. {
  386. return "";
  387. }
  388. str = str.Replace("&acute;", "'");
  389. str = str.Replace("&quot;", "\"");
  390. //str = str.Replace("&nbsp;", " ");
  391. str = str.Replace("&lt;", "<");
  392. str = str.Replace("&gt;", ">");
  393. str = str.Replace("(", "(");
  394. str = str.Replace(")", ")");
  395. return str;
  396. }
  397. public static string CheckString2(string str)
  398. {
  399. if (str == null || str == string.Empty)
  400. {
  401. return "";
  402. }
  403. str = ToDBC(str);
  404. str = Regex.Replace(str, @"<script.*?>[\s\S]*?</script>", "", RegexOptions.IgnoreCase);
  405. str = Regex.Replace(str, @"<script.*?>", "", RegexOptions.IgnoreCase);
  406. str = Regex.Replace(str, @"<object.*?>[\s\S]*?</object>", "", RegexOptions.IgnoreCase);
  407. str = Regex.Replace(str, @"<object.*?>", "", RegexOptions.IgnoreCase);
  408. str = Regex.Replace(str, @"<iframe.*?>[\s\S]*?</iframe>", "", RegexOptions.IgnoreCase);
  409. str = Regex.Replace(str, @"<frameset.*?>[\s\S]*?</frameset>", "", RegexOptions.IgnoreCase);
  410. str = Regex.Replace(str, @"<frameset.*?>", "", RegexOptions.IgnoreCase);
  411. str = Regex.Replace(str, @"<frame.*?>[\s\S]*?</frame>", "", RegexOptions.IgnoreCase);
  412. str = Regex.Replace(str, @"<frame.*?>", "", RegexOptions.IgnoreCase);
  413. str = Regex.Replace(str, @"<form.*?>[\s\S]*?</form>", "", RegexOptions.IgnoreCase);
  414. str = Regex.Replace(str, @"<input.*?>", "", RegexOptions.IgnoreCase);
  415. str = Regex.Replace(str, @"<select.*?>[\s\S]*?</select>", "", RegexOptions.IgnoreCase);
  416. str = Regex.Replace(str, @"<textarea.*?>[\s\S]*?</textarea>", "", RegexOptions.IgnoreCase);
  417. str = Regex.Replace(str, @"<button.*?>", "", RegexOptions.IgnoreCase);
  418. str = Regex.Replace(str, @"<noframes.*?>[\s\S]*?</noframes>", "", RegexOptions.IgnoreCase);
  419. str = Regex.Replace(str, @"<noframes.*?>", "", RegexOptions.IgnoreCase);
  420. return str;
  421. }
  422. public static string GetSession(HttpContext context, string strName)
  423. {
  424. var value = context.Session.GetString(strName);
  425. if (string.IsNullOrEmpty(value))
  426. {
  427. value = "";
  428. }
  429. return value;
  430. }
  431. public static void WriteSession(HttpContext context, string strName, string strValue)
  432. {
  433. context.Session.SetString(strName, strValue);
  434. }
  435. public static void DelSession(HttpContext context, string strName)
  436. {
  437. context.Session.Remove(strName);
  438. }
  439. public static string rootIndex = System.AppDomain.CurrentDomain.BaseDirectory;
  440. private static string Read(string absoluteFileLocation)
  441. {
  442. string result = "";
  443. if (System.IO.File.Exists(absoluteFileLocation))
  444. {
  445. using (FileStream fs = new FileStream(absoluteFileLocation, FileMode.Open, FileAccess.Read))
  446. {
  447. using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8))
  448. {
  449. try
  450. {
  451. result = sr.ReadToEnd();
  452. //dbconn.InsertCache(absoluteFileLocation, result, 30);
  453. }
  454. catch
  455. { }
  456. }
  457. }
  458. }
  459. return result;
  460. }
  461. public static string getPath(string path_str)
  462. {
  463. string result = AppContext.BaseDirectory + path_str;
  464. return result;
  465. }
  466. public static string getProPath(string path_str)
  467. {
  468. string result = Path.GetFullPath(path_str);
  469. return result;
  470. }
  471. public static string ReadInstance(string path_str)
  472. {
  473. //string path = System.IO.Path.Combine(rootIndex, path_str).Replace('/', System.IO.Path.DirectorySeparatorChar);
  474. string path = getPath(path_str);
  475. string content = "";
  476. content = Read(path);
  477. return content;
  478. }
  479. public static string ReadInstanceNoAuth(string path_str)
  480. {
  481. //string path = System.IO.Path.Combine(rootIndex, path_str).Replace('/', System.IO.Path.DirectorySeparatorChar);
  482. string path = getPath(path_str);
  483. string content = "";
  484. content = Read(path);
  485. return content;
  486. }
  487. public static string ReadInstanceByFull(string path_str)
  488. {
  489. string content = "";
  490. content = Read(path_str);
  491. return content;
  492. }
  493. public static void WritePage(string path_str, string file_name, string page_content)
  494. {
  495. try
  496. {
  497. string path = getPath(path_str);
  498. if (!Directory.Exists(path))
  499. {
  500. Directory.CreateDirectory(path);
  501. }
  502. Encoding nobom = new UTF8Encoding(false, false);
  503. StreamWriter sw = new StreamWriter(path + "/" + file_name, false, nobom);
  504. sw.Write(page_content);
  505. sw.Flush();
  506. sw.Dispose();
  507. }
  508. catch
  509. { }
  510. }
  511. public static void WritePageFullPath(string path_str, string file_name, string page_content)
  512. {
  513. try
  514. {
  515. if (!Directory.Exists(path_str))
  516. {
  517. Directory.CreateDirectory(path_str);
  518. }
  519. Encoding nobom = new UTF8Encoding(false, false);
  520. StreamWriter sw = new StreamWriter(path_str + file_name, false, nobom);
  521. sw.Write(page_content);
  522. sw.Flush();
  523. sw.Dispose();
  524. }
  525. catch
  526. { }
  527. }
  528. public static void send_email(string mailTitle, string mailTo, string mailContent, string file_path, string host, int port, string username, string pwd, string displayname)
  529. {
  530. try
  531. {
  532. MailAddress from = new MailAddress(username, displayname); //邮件的发件人
  533. MailMessage mail = new MailMessage();
  534. //设置邮件的标题
  535. mail.Subject = mailTitle;
  536. mail.SubjectEncoding = Encoding.UTF8;
  537. //设置邮件的发件人
  538. //Pass:如果不想显示自己的邮箱地址,这里可以填符合mail格式的任意名称,真正发mail的用户不在这里设定,这个仅仅只做显示用
  539. mail.From = from;
  540. //设置邮件的收件人
  541. string address = "";
  542. string displayName = "";
  543. /**/
  544. /* 这里这样写是因为可能发给多个联系人,每个地址用 ; 号隔开
  545. 一般从地址簿中直接选择联系人的时候格式都会是 :用户名1 < mail1 >; 用户名2 < mail 2>;
  546. 因此就有了下面一段逻辑不太好的代码
  547. 如果永远都只需要发给一个收件人那么就简单了 mail.To.Add("收件人mail");
  548. */
  549. string[] mailNames = (mailTo + ";").Split(';');
  550. foreach (string name in mailNames)
  551. {
  552. if (name != string.Empty)
  553. {
  554. if (name.IndexOf('<') > 0)
  555. {
  556. displayName = name.Substring(0, name.IndexOf('<'));
  557. address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
  558. }
  559. else
  560. {
  561. displayName = string.Empty;
  562. address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
  563. }
  564. mail.To.Add(new MailAddress(address, displayName));
  565. }
  566. }
  567. //设置邮件的抄送收件人
  568. //这个就简单多了,如果不想快点下岗重要文件还是CC一份给领导比较好
  569. //mail.CC.Add(new MailAddress("Manage@hotmail.com", "尊敬的领导"));
  570. //设置邮件的内容
  571. mail.Body = mailContent;
  572. //设置邮件的格式
  573. mail.BodyEncoding = Encoding.UTF8;
  574. mail.IsBodyHtml = true;
  575. //设置邮件的发送级别
  576. mail.Priority = MailPriority.Normal;
  577. //设置邮件的附件,将在客户端选择的附件先上传到服务器保存一个,然后加入到mail中
  578. //string fileName = file_path;
  579. //fileName = "D:/UpFile/" + fileName.Substring(fileName.LastIndexOf("/") + 1);
  580. //txtUpFile.PostedFile.SaveAs(fileName); // 将文件保存至服务器
  581. //mail.Attachments.Add(new Attachment(fileName));
  582. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
  583. SmtpClient client = new SmtpClient();
  584. //设置用于 SMTP 事务的主机的名称,填IP地址也可以了
  585. //client.Host = "smtp.163.com";
  586. client.Host = host;
  587. //设置用于 SMTP 事务的端口,默认的是 25
  588. //client.Port = 25;
  589. client.Port = port;
  590. client.UseDefaultCredentials = false;
  591. client.EnableSsl = true;
  592. //这里才是真正的邮箱登陆名和密码,比如我的邮箱地址是 hbgx@hotmail, 我的用户名为 hbgx ,我的密码是 xgbh
  593. client.Credentials = new System.Net.NetworkCredential(username, pwd);
  594. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  595. client.Send(mail);
  596. }
  597. catch (Exception ex)
  598. {
  599. Function.WriteLog(ex.ToString());
  600. }
  601. }
  602. public static string GetWebRequest(string url)
  603. {
  604. return GetWebRequest(url, new Dictionary<string, string>());
  605. }
  606. public static string GetWebRequest(string url, Dictionary<string, string> header)
  607. {
  608. string result = "";
  609. try
  610. {
  611. HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(url);
  612. webReq.Method = "GET";
  613. webReq.KeepAlive = true;
  614. webReq.Timeout = 1200000;
  615. webReq.ContentType = "text/html";//application/x-www-form-urlencoded
  616. if (header.Count > 0)
  617. {
  618. foreach (string key in header.Keys)
  619. {
  620. webReq.Headers.Add(key, header[key]);
  621. }
  622. }
  623. webReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
  624. using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
  625. {
  626. using (StreamReader reader = new StreamReader(response.GetResponseStream()))
  627. {
  628. result = reader.ReadToEnd();
  629. //function.WriteLog(context.Request.QueryString["mobile"] + " " + reader.ReadToEnd());
  630. }
  631. if (response != null)
  632. response.Close();
  633. }
  634. }
  635. catch (Exception ex)
  636. {
  637. result = ex.ToString();
  638. }
  639. return result;
  640. }
  641. public static string get_Random(int num)
  642. {
  643. string[] str = new string[num];
  644. string serverCode = "";
  645. //生成随机生成器
  646. Random random = new Random(GetRandomSeed());
  647. for (int i = 0; i < num; i++)
  648. {
  649. str[i] = random.Next(10).ToString().Substring(0, 1);
  650. }
  651. foreach (string s in str)
  652. {
  653. serverCode += s;
  654. }
  655. return serverCode;
  656. }
  657. public static int get_Random(int min, int max)
  658. {
  659. int serverCode = 0;
  660. Random random = new Random(GetRandomSeed());
  661. serverCode = random.Next(max - min) + min;
  662. return serverCode;
  663. }
  664. public static string get_Random_string(int count)
  665. {
  666. string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  667. string result = "";
  668. for (int i = 0; i < count; i++)
  669. {
  670. Random r = new Random(GetRandomSeed());
  671. int serverCode = r.Next(str.Length - 0) + 0;
  672. result += str.Substring(serverCode, 1);
  673. }
  674. return result;
  675. }
  676. public static int GetRandomSeed()
  677. {
  678. //字节数组,用于存储
  679. byte[] bytes = new byte[4];
  680. //创建加密服务,实现加密随机数生成器
  681. System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
  682. //加密数据存入字节数组
  683. rng.GetBytes(bytes);
  684. //转成整型数据返回,作为随机数生成种子
  685. return BitConverter.ToInt32(bytes, 0);
  686. }
  687. public static string get_weekday(DateTime date)
  688. {
  689. string[] week = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
  690. return week[(int)date.DayOfWeek];
  691. }
  692. public static string get_substr(string s, int length)
  693. {
  694. byte[] bytes = System.Text.Encoding.Unicode.GetBytes(s);
  695. int n = 0; // 表示当前的字节数
  696. int i = 0; // 要截取的字节数
  697. for (; i < bytes.GetLength(0) && n < length; i++)
  698. {
  699. // 偶数位置,如0、2、4等,为UCS2编码中两个字节的第一个字节
  700. if (i % 2 == 0)
  701. {
  702. n++; // 在UCS2第一个字节时n加1
  703. }
  704. else
  705. {
  706. // 当UCS2编码的第二个字节大于0时,该UCS2字符为汉字,一个汉字算两个字节
  707. if (bytes[i] > 0)
  708. {
  709. n++;
  710. }
  711. }
  712. }
  713. // 如果i为奇数时,处理成偶数
  714. if (i % 2 == 1)
  715. {
  716. // 该UCS2字符是汉字时,去掉这个截一半的汉字
  717. if (bytes[i] > 0)
  718. i = i - 1;
  719. // 该UCS2字符是字母或数字,则保留该字符
  720. else
  721. i = i + 1;
  722. }
  723. return System.Text.Encoding.Unicode.GetString(bytes, 0, i);
  724. }
  725. public static DateTime ConvertIntDateTime(double d)
  726. {
  727. DateTime time = DateTime.MinValue;
  728. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  729. time = startTime.AddSeconds(d);
  730. return time;
  731. }
  732. public static DateTime ConvertIntDateTimeMini(long TimeStamp)
  733. {
  734. System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
  735. return startTime.AddTicks(TimeStamp * 10000);
  736. }
  737. public static int ConvertDateTimeInt(DateTime time)
  738. {
  739. double intResult = 0;
  740. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  741. TimeSpan ts = time - startTime;
  742. intResult = Math.Round(ts.TotalSeconds, 0);
  743. return int.Parse(intResult.ToString());
  744. }
  745. public static long GetCurTimestamp()
  746. {
  747. var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  748. long times = Convert.ToInt64(ts.TotalMilliseconds);
  749. return times;
  750. }
  751. public static DateTime checkDateTimeNull(DateTime? datetime)
  752. {
  753. if (datetime != null)
  754. {
  755. return datetime.Value;
  756. }
  757. return DateTime.Now;
  758. }
  759. public static bool IsDate(string datetime)
  760. {
  761. DateTime check = DateTime.Now;
  762. return DateTime.TryParse(datetime + " 00:00:00", out check);
  763. }
  764. public static bool IsDateTime(string datetime)
  765. {
  766. DateTime check = DateTime.Now;
  767. return DateTime.TryParse(datetime, out check);
  768. }
  769. /// <summary>
  770. /// 获取时间戳
  771. /// </summary>
  772. /// <returns></returns>
  773. public static string getTimeStamp()
  774. {
  775. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  776. return Convert.ToInt64(ts.TotalSeconds).ToString();
  777. }
  778. public static string get_timespan(DateTime s, string show_type)
  779. {
  780. string result = get_timespan(s, DateTime.Now, show_type);
  781. return result;
  782. }
  783. public static string get_timespan(DateTime s, DateTime e, string show_type)
  784. {
  785. string result = "";
  786. if (e > s)
  787. {
  788. int total = 0;
  789. TimeSpan ts = e - s;
  790. switch (show_type)
  791. {
  792. case "d":
  793. result = ts.Days.ToString() + "天";
  794. break;
  795. case "h":
  796. if (ts.Days > 0)
  797. {
  798. total += ts.Days * 24;
  799. }
  800. total += ts.Hours;
  801. result = total.ToString() + "小时";
  802. break;
  803. case "m":
  804. if (ts.Days > 0)
  805. {
  806. total += ts.Days * 24 * 60;
  807. }
  808. if (ts.Hours > 0)
  809. {
  810. total += ts.Hours * 60;
  811. }
  812. total += ts.Hours;
  813. result = total.ToString() + "分钟";
  814. break;
  815. case "s":
  816. if (ts.Days > 0)
  817. {
  818. total += ts.Days * 24 * 60 * 60;
  819. }
  820. if (ts.Hours > 0)
  821. {
  822. total += ts.Hours * 60 * 60;
  823. }
  824. if (ts.Minutes > 0)
  825. {
  826. total += ts.Hours * 60;
  827. }
  828. total += ts.Hours;
  829. result = total.ToString() + "秒";
  830. break;
  831. case "time":
  832. if (ts.Days > 1)
  833. {
  834. result = s.ToString("yyyy-MM-dd");
  835. }
  836. else
  837. {
  838. if (ts.Days > 0)
  839. {
  840. result += ts.Days + "天";
  841. }
  842. if (ts.Hours > 0)
  843. {
  844. result += ts.Hours + "小时";
  845. }
  846. if (ts.Minutes > 0)
  847. {
  848. result += ts.Minutes + "分钟";
  849. }
  850. if (string.IsNullOrEmpty(result))
  851. {
  852. result = "刚刚";
  853. }
  854. else
  855. {
  856. result += "前";
  857. }
  858. }
  859. break;
  860. default: break;
  861. }
  862. }
  863. return result;
  864. }
  865. // 半角转全角
  866. public static string ToSBC(string input)
  867. {
  868. char[] c = input.ToCharArray();
  869. for (int i = 0; i < c.Length; i++)
  870. {
  871. if (c[i] == 32)
  872. {
  873. c[i] = (char)12288;
  874. continue;
  875. }
  876. if (c[i] < 127)
  877. c[i] = (char)(c[i] + 65248);
  878. }
  879. return new string(c);
  880. }
  881. // 全角转半角
  882. public static string ToDBC(string input)
  883. {
  884. char[] c = input.ToCharArray();
  885. for (int i = 0; i < c.Length; i++)
  886. {
  887. if (c[i] == 12288)
  888. {
  889. c[i] = (char)32;
  890. continue;
  891. }
  892. if (c[i] > 65280 && c[i] < 65375)
  893. c[i] = (char)(c[i] - 65248);
  894. }
  895. return new string(c);
  896. }
  897. public static string PostWebRequest(string postUrl, string paramData, string ContentType = "application/x-www-form-urlencoded")
  898. {
  899. //return PostWebRequest(postUrl, paramData, new Dictionary<string, string>());
  900. string ret = string.Empty;
  901. try
  902. {
  903. byte[] postData = Encoding.UTF8.GetBytes(paramData);
  904. // 设置提交的相关参数
  905. HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
  906. Encoding myEncoding = Encoding.UTF8;
  907. request.Method = "POST";
  908. request.KeepAlive = false;
  909. request.AllowAutoRedirect = true;
  910. request.ContentType = ContentType;
  911. //request.ContentType = "multipart/form-data; boundary=" + boundary;
  912. request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
  913. request.ContentLength = postData.Length;
  914. // 提交请求数据
  915. System.IO.Stream outputStream = request.GetRequestStream();
  916. outputStream.Write(postData, 0, postData.Length);
  917. outputStream.Close();
  918. HttpWebResponse response;
  919. Stream responseStream;
  920. StreamReader reader;
  921. string srcString;
  922. response = request.GetResponse() as HttpWebResponse;
  923. responseStream = response.GetResponseStream();
  924. reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
  925. srcString = reader.ReadToEnd();
  926. ret = srcString; //返回值赋值
  927. reader.Close();
  928. }
  929. catch (Exception ex)
  930. {
  931. ret = "fail";
  932. WriteLog(ex.ToString(), "PostWebRequest");
  933. }
  934. return ret;
  935. }
  936. public static string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> header, string ContentType = "application/x-www-form-urlencoded")
  937. {
  938. //return PostWebRequest(postUrl, paramData, new Dictionary<string, string>());
  939. string ret = string.Empty;
  940. try
  941. {
  942. byte[] postData = Encoding.UTF8.GetBytes(paramData);
  943. // 设置提交的相关参数
  944. HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
  945. Encoding myEncoding = Encoding.UTF8;
  946. request.Method = "POST";
  947. request.KeepAlive = false;
  948. request.AllowAutoRedirect = true;
  949. request.ContentType = ContentType;
  950. //request.ContentType = "multipart/form-data; boundary=" + boundary;
  951. request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
  952. request.ContentLength = postData.Length;
  953. if (header.Count > 0)
  954. {
  955. foreach (string key in header.Keys)
  956. {
  957. request.Headers.Add(key, header[key]);
  958. }
  959. }
  960. // 提交请求数据
  961. System.IO.Stream outputStream = request.GetRequestStream();
  962. outputStream.Write(postData, 0, postData.Length);
  963. outputStream.Close();
  964. HttpWebResponse response;
  965. Stream responseStream;
  966. StreamReader reader;
  967. string srcString;
  968. response = request.GetResponse() as HttpWebResponse;
  969. responseStream = response.GetResponseStream();
  970. reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
  971. srcString = reader.ReadToEnd();
  972. ret = srcString; //返回值赋值
  973. reader.Close();
  974. }
  975. catch (Exception ex)
  976. {
  977. ret = "fail";
  978. WriteLog(ex.ToString(), "PostWebRequest");
  979. }
  980. return ret;
  981. }
  982. /// <summary>
  983. /// 从ftp服务器上获得文件夹列表
  984. /// </summary>
  985. /// <param name="RequedstPath">服务器下的相对路径</param>
  986. /// <returns></returns>
  987. public static List<string> GetFtpDirctoryList(string path, string username, string password)
  988. {
  989. List<string> strs = new List<string>();
  990. try
  991. {
  992. string uri = path; //目标路径 path为服务器地址
  993. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  994. // ftp用户名和密码
  995. reqFTP.Credentials = new NetworkCredential(username, password);
  996. reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  997. WebResponse response = reqFTP.GetResponse();
  998. StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
  999. string line = reader.ReadLine();
  1000. while (line != null)
  1001. {
  1002. if (line.Contains("<DIR>"))
  1003. {
  1004. string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
  1005. strs.Add(msg);
  1006. }
  1007. line = reader.ReadLine();
  1008. }
  1009. reader.Close();
  1010. response.Close();
  1011. return strs;
  1012. }
  1013. catch (Exception ex)
  1014. {
  1015. Function.WriteLog(DateTime.Now + ":" + ex.ToString(), "从ftp服务器上获得文件夹列表异常");
  1016. }
  1017. return strs;
  1018. }
  1019. /// <summary>
  1020. /// 从ftp服务器上获得文件列表
  1021. /// </summary>
  1022. /// <param name="RequedstPath">服务器下的相对路径</param>
  1023. /// <returns></returns>
  1024. public static List<string> GetFtpFileList(string path, string username, string password)
  1025. {
  1026. List<string> strs = new List<string>();
  1027. try
  1028. {
  1029. string uri = path; //目标路径 path为服务器地址
  1030. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  1031. // ftp用户名和密码
  1032. reqFTP.Credentials = new NetworkCredential(username, password);
  1033. reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  1034. WebResponse response = reqFTP.GetResponse();
  1035. StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
  1036. string line = reader.ReadLine();
  1037. while (line != null)
  1038. {
  1039. if (!line.Contains("<DIR>"))
  1040. {
  1041. string msg = line.Substring(39).Trim();
  1042. strs.Add(msg);
  1043. }
  1044. line = reader.ReadLine();
  1045. }
  1046. reader.Close();
  1047. response.Close();
  1048. return strs;
  1049. }
  1050. catch (Exception ex)
  1051. {
  1052. Function.WriteLog(DateTime.Now + ":" + ex.ToString(), "从ftp服务器上获得文件列表异常");
  1053. }
  1054. return strs;
  1055. }
  1056. //从ftp服务器上下载文件
  1057. public static string FtpDownload(string path, string fileName, string username, string password)
  1058. {
  1059. FtpWebRequest reqFTP;
  1060. string savePath = "";
  1061. try
  1062. {
  1063. string filePath = getPath("/FtpDownloadFile/" + fileName);
  1064. FileStream outputStream = new FileStream(filePath, FileMode.Create);
  1065. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + fileName));
  1066. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  1067. reqFTP.UseBinary = true;
  1068. reqFTP.Credentials = new NetworkCredential(username, password);
  1069. reqFTP.UsePassive = false;
  1070. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  1071. Stream ftpStream = response.GetResponseStream();
  1072. long cl = response.ContentLength;
  1073. int bufferSize = 2048;
  1074. int readCount;
  1075. byte[] buffer = new byte[bufferSize];
  1076. readCount = ftpStream.Read(buffer, 0, bufferSize);
  1077. while (readCount > 0)
  1078. {
  1079. outputStream.Write(buffer, 0, readCount);
  1080. readCount = ftpStream.Read(buffer, 0, bufferSize);
  1081. }
  1082. ftpStream.Close();
  1083. outputStream.Close();
  1084. response.Close();
  1085. savePath = "/FtpDownloadFile/" + fileName;
  1086. }
  1087. catch (Exception ex)
  1088. {
  1089. Function.WriteLog(DateTime.Now + ":" + ex.ToString(), "从ftp服务器上下载文件异常");
  1090. }
  1091. return savePath;
  1092. }
  1093. public static string base64StringToImage(string base64String, string path, string filename)
  1094. {
  1095. string fullpath = getPath(path);
  1096. if (!System.IO.Directory.Exists(fullpath))
  1097. {
  1098. System.IO.Directory.CreateDirectory(fullpath);
  1099. }
  1100. byte[] arr = Convert.FromBase64String(base64String);
  1101. System.IO.File.WriteAllBytes(fullpath + filename, arr);
  1102. return path + filename;
  1103. }
  1104. public static String BuildQueryString(SortedList<String, String> kvp)
  1105. {
  1106. return String.Join("&", kvp.Select(item => String.Format("{0}={1}", item.Key.Trim(), item.Value)).ToArray());
  1107. }
  1108. #region 获取网络文件内容
  1109. public static string GetNetFileContent(string url)
  1110. {
  1111. string textContent = "";
  1112. using (var client = new WebClient())
  1113. {
  1114. try
  1115. {
  1116. textContent = client.DownloadString(url); // 通过 DownloadString 方法获取网页内容
  1117. }
  1118. catch (Exception ex)
  1119. {
  1120. WriteLog(DateTime.Now.ToString() + "\n" + url + "\n" + ex.ToString() + "\n\n", "获取网络文件内容异常");
  1121. }
  1122. }
  1123. return textContent;
  1124. }
  1125. public static byte[] GetNetFileData(string url)
  1126. {
  1127. byte[] textContent = new byte[] { };
  1128. using (var client = new WebClient())
  1129. {
  1130. try
  1131. {
  1132. textContent = client.DownloadData(url); // 通过 DownloadString 方法获取网页内容
  1133. }
  1134. catch (Exception ex)
  1135. {
  1136. WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "获取网络文件流异常");
  1137. }
  1138. }
  1139. return textContent;
  1140. }
  1141. #endregion
  1142. public static string ReplaceLast(string source, string oldStr, string newStr)
  1143. {
  1144. if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(oldStr))
  1145. return source;
  1146. int index = source.LastIndexOf(oldStr);
  1147. if (index == -1) return source;
  1148. return source.Substring(0, index) + newStr + source.Substring(index + oldStr.Length);
  1149. }
  1150. public static string ReplaceFirst(string source, string oldStr, string newStr)
  1151. {
  1152. if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(oldStr))
  1153. return source;
  1154. int index = source.IndexOf(oldStr);
  1155. if (index == -1)
  1156. return source;
  1157. return source.Substring(0, index) + newStr + source.Substring(index + oldStr.Length);
  1158. }
  1159. public static void DownloadNetFile(string url, string savePath)
  1160. {
  1161. using (var client = new WebClient())
  1162. {
  1163. try
  1164. {
  1165. string dir = savePath.Substring(0, savePath.LastIndexOf("/"));
  1166. if (!System.IO.Directory.Exists(dir))
  1167. {
  1168. System.IO.Directory.CreateDirectory(dir);
  1169. }
  1170. client.DownloadFile(url, savePath); // 通过 DownloadString 方法获取网页内容
  1171. }
  1172. catch (Exception ex)
  1173. {
  1174. Utils.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "下载网络文件异常");
  1175. }
  1176. }
  1177. }
  1178. }
  1179. }