Function.cs 48 KB

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