Function.cs 45 KB

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