Function.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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 ReadInstance(string path_str)
  467. {
  468. //string path = System.IO.Path.Combine(rootIndex, path_str).Replace('/', System.IO.Path.DirectorySeparatorChar);
  469. string path = getPath(path_str);
  470. string content = "";
  471. content = Read(path);
  472. return content;
  473. }
  474. public static string ReadInstanceNoAuth(string path_str)
  475. {
  476. //string path = System.IO.Path.Combine(rootIndex, path_str).Replace('/', System.IO.Path.DirectorySeparatorChar);
  477. string path = getPath(path_str);
  478. string content = "";
  479. content = Read(path);
  480. return content;
  481. }
  482. public static string ReadInstanceByFull(string path_str)
  483. {
  484. string content = "";
  485. content = Read(path_str);
  486. return content;
  487. }
  488. public static void WritePage(string path_str, string file_name, string page_content)
  489. {
  490. try
  491. {
  492. string path = getPath(path_str);
  493. if (!Directory.Exists(path))
  494. {
  495. Directory.CreateDirectory(path);
  496. }
  497. Encoding nobom = new UTF8Encoding(false, false);
  498. StreamWriter sw = new StreamWriter(path + "/" + file_name, false, nobom);
  499. sw.Write(page_content);
  500. sw.Flush();
  501. sw.Dispose();
  502. }
  503. catch
  504. { }
  505. }
  506. public static void WritePageFullPath(string path_str, string file_name, string page_content)
  507. {
  508. try
  509. {
  510. if (!Directory.Exists(path_str))
  511. {
  512. Directory.CreateDirectory(path_str);
  513. }
  514. Encoding nobom = new UTF8Encoding(false, false);
  515. StreamWriter sw = new StreamWriter(path_str + file_name, false, nobom);
  516. sw.Write(page_content);
  517. sw.Flush();
  518. sw.Dispose();
  519. }
  520. catch
  521. { }
  522. }
  523. public static void send_email(string mailTitle, string mailTo, string mailContent, string file_path, string host, int port, string username, string pwd, string displayname)
  524. {
  525. try
  526. {
  527. MailAddress from = new MailAddress(username, displayname); //邮件的发件人
  528. MailMessage mail = new MailMessage();
  529. //设置邮件的标题
  530. mail.Subject = mailTitle;
  531. mail.SubjectEncoding = Encoding.UTF8;
  532. //设置邮件的发件人
  533. //Pass:如果不想显示自己的邮箱地址,这里可以填符合mail格式的任意名称,真正发mail的用户不在这里设定,这个仅仅只做显示用
  534. mail.From = from;
  535. //设置邮件的收件人
  536. string address = "";
  537. string displayName = "";
  538. /**/
  539. /* 这里这样写是因为可能发给多个联系人,每个地址用 ; 号隔开
  540. 一般从地址簿中直接选择联系人的时候格式都会是 :用户名1 < mail1 >; 用户名2 < mail 2>;
  541. 因此就有了下面一段逻辑不太好的代码
  542. 如果永远都只需要发给一个收件人那么就简单了 mail.To.Add("收件人mail");
  543. */
  544. string[] mailNames = (mailTo + ";").Split(';');
  545. foreach (string name in mailNames)
  546. {
  547. if (name != string.Empty)
  548. {
  549. if (name.IndexOf('<') > 0)
  550. {
  551. displayName = name.Substring(0, name.IndexOf('<'));
  552. address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
  553. }
  554. else
  555. {
  556. displayName = string.Empty;
  557. address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
  558. }
  559. mail.To.Add(new MailAddress(address, displayName));
  560. }
  561. }
  562. //设置邮件的抄送收件人
  563. //这个就简单多了,如果不想快点下岗重要文件还是CC一份给领导比较好
  564. //mail.CC.Add(new MailAddress("Manage@hotmail.com", "尊敬的领导"));
  565. //设置邮件的内容
  566. mail.Body = mailContent;
  567. //设置邮件的格式
  568. mail.BodyEncoding = Encoding.UTF8;
  569. mail.IsBodyHtml = true;
  570. //设置邮件的发送级别
  571. mail.Priority = MailPriority.Normal;
  572. //设置邮件的附件,将在客户端选择的附件先上传到服务器保存一个,然后加入到mail中
  573. //string fileName = file_path;
  574. //fileName = "D:/UpFile/" + fileName.Substring(fileName.LastIndexOf("/") + 1);
  575. //txtUpFile.PostedFile.SaveAs(fileName); // 将文件保存至服务器
  576. //mail.Attachments.Add(new Attachment(fileName));
  577. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
  578. SmtpClient client = new SmtpClient();
  579. //设置用于 SMTP 事务的主机的名称,填IP地址也可以了
  580. //client.Host = "smtp.163.com";
  581. client.Host = host;
  582. //设置用于 SMTP 事务的端口,默认的是 25
  583. //client.Port = 25;
  584. client.Port = port;
  585. client.UseDefaultCredentials = false;
  586. client.EnableSsl = true;
  587. //这里才是真正的邮箱登陆名和密码,比如我的邮箱地址是 hbgx@hotmail, 我的用户名为 hbgx ,我的密码是 xgbh
  588. client.Credentials = new System.Net.NetworkCredential(username, pwd);
  589. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  590. client.Send(mail);
  591. }
  592. catch (Exception ex)
  593. {
  594. Function.WriteLog(ex.ToString());
  595. }
  596. }
  597. public static string GetWebRequest(string url)
  598. {
  599. return GetWebRequest(url, new Dictionary<string, string>());
  600. }
  601. public static string GetWebRequest(string url, Dictionary<string, string> header)
  602. {
  603. string result = "";
  604. try
  605. {
  606. HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(url);
  607. webReq.Method = "GET";
  608. webReq.KeepAlive = true;
  609. webReq.Timeout = 1200000;
  610. webReq.ContentType = "text/html";//application/x-www-form-urlencoded
  611. if (header.Count > 0)
  612. {
  613. foreach (string key in header.Keys)
  614. {
  615. webReq.Headers.Add(key, header[key]);
  616. }
  617. }
  618. webReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
  619. using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
  620. {
  621. using (StreamReader reader = new StreamReader(response.GetResponseStream()))
  622. {
  623. result = reader.ReadToEnd();
  624. //function.WriteLog(context.Request.QueryString["mobile"] + " " + reader.ReadToEnd());
  625. }
  626. if (response != null)
  627. response.Close();
  628. }
  629. }
  630. catch (Exception ex)
  631. {
  632. result = ex.ToString();
  633. }
  634. return result;
  635. }
  636. public static string get_Random(int num)
  637. {
  638. string[] str = new string[num];
  639. string serverCode = "";
  640. //生成随机生成器
  641. Random random = new Random(GetRandomSeed());
  642. for (int i = 0; i < num; i++)
  643. {
  644. str[i] = random.Next(10).ToString().Substring(0, 1);
  645. }
  646. foreach (string s in str)
  647. {
  648. serverCode += s;
  649. }
  650. return serverCode;
  651. }
  652. public static int get_Random(int min, int max)
  653. {
  654. int serverCode = 0;
  655. Random random = new Random(GetRandomSeed());
  656. serverCode = random.Next(max - min) + min;
  657. return serverCode;
  658. }
  659. public static string get_Random_string(int count)
  660. {
  661. string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  662. string result = "";
  663. for (int i = 0; i < count; i++)
  664. {
  665. Random r = new Random(GetRandomSeed());
  666. int serverCode = r.Next(str.Length - 0) + 0;
  667. result += str.Substring(serverCode, 1);
  668. }
  669. return result;
  670. }
  671. public static int GetRandomSeed()
  672. {
  673. //字节数组,用于存储
  674. byte[] bytes = new byte[4];
  675. //创建加密服务,实现加密随机数生成器
  676. System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
  677. //加密数据存入字节数组
  678. rng.GetBytes(bytes);
  679. //转成整型数据返回,作为随机数生成种子
  680. return BitConverter.ToInt32(bytes, 0);
  681. }
  682. public static string get_weekday(DateTime date)
  683. {
  684. string[] week = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
  685. return week[(int)date.DayOfWeek];
  686. }
  687. public static string get_substr(string s, int length)
  688. {
  689. byte[] bytes = System.Text.Encoding.Unicode.GetBytes(s);
  690. int n = 0; // 表示当前的字节数
  691. int i = 0; // 要截取的字节数
  692. for (; i < bytes.GetLength(0) && n < length; i++)
  693. {
  694. // 偶数位置,如0、2、4等,为UCS2编码中两个字节的第一个字节
  695. if (i % 2 == 0)
  696. {
  697. n++; // 在UCS2第一个字节时n加1
  698. }
  699. else
  700. {
  701. // 当UCS2编码的第二个字节大于0时,该UCS2字符为汉字,一个汉字算两个字节
  702. if (bytes[i] > 0)
  703. {
  704. n++;
  705. }
  706. }
  707. }
  708. // 如果i为奇数时,处理成偶数
  709. if (i % 2 == 1)
  710. {
  711. // 该UCS2字符是汉字时,去掉这个截一半的汉字
  712. if (bytes[i] > 0)
  713. i = i - 1;
  714. // 该UCS2字符是字母或数字,则保留该字符
  715. else
  716. i = i + 1;
  717. }
  718. return System.Text.Encoding.Unicode.GetString(bytes, 0, i);
  719. }
  720. public static DateTime ConvertIntDateTime(double d)
  721. {
  722. DateTime time = DateTime.MinValue;
  723. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  724. time = startTime.AddSeconds(d);
  725. return time;
  726. }
  727. public static DateTime ConvertIntDateTimeMini(long TimeStamp)
  728. {
  729. System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
  730. return startTime.AddTicks(TimeStamp * 10000);
  731. }
  732. public static int ConvertDateTimeInt(DateTime time)
  733. {
  734. double intResult = 0;
  735. DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  736. TimeSpan ts = time - startTime;
  737. intResult = Math.Round(ts.TotalSeconds, 0);
  738. return int.Parse(intResult.ToString());
  739. }
  740. public static long GetCurTimestamp()
  741. {
  742. var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  743. long times = Convert.ToInt64(ts.TotalMilliseconds);
  744. return times;
  745. }
  746. public static DateTime checkDateTimeNull(DateTime? datetime)
  747. {
  748. if (datetime != null)
  749. {
  750. return datetime.Value;
  751. }
  752. return DateTime.Now;
  753. }
  754. public static bool IsDate(string datetime)
  755. {
  756. DateTime check = DateTime.Now;
  757. return DateTime.TryParse(datetime + " 00:00:00", out check);
  758. }
  759. public static bool IsDateTime(string datetime)
  760. {
  761. DateTime check = DateTime.Now;
  762. return DateTime.TryParse(datetime, out check);
  763. }
  764. /// <summary>
  765. /// 获取时间戳
  766. /// </summary>
  767. /// <returns></returns>
  768. public static string getTimeStamp()
  769. {
  770. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  771. return Convert.ToInt64(ts.TotalSeconds).ToString();
  772. }
  773. public static string get_timespan(DateTime s, string show_type)
  774. {
  775. string result = get_timespan(s, DateTime.Now, show_type);
  776. return result;
  777. }
  778. public static string get_timespan(DateTime s, DateTime e, string show_type)
  779. {
  780. string result = "";
  781. if (e > s)
  782. {
  783. int total = 0;
  784. TimeSpan ts = e - s;
  785. switch (show_type)
  786. {
  787. case "d":
  788. result = ts.Days.ToString() + "天";
  789. break;
  790. case "h":
  791. if (ts.Days > 0)
  792. {
  793. total += ts.Days * 24;
  794. }
  795. total += ts.Hours;
  796. result = total.ToString() + "小时";
  797. break;
  798. case "m":
  799. if (ts.Days > 0)
  800. {
  801. total += ts.Days * 24 * 60;
  802. }
  803. if (ts.Hours > 0)
  804. {
  805. total += ts.Hours * 60;
  806. }
  807. total += ts.Hours;
  808. result = total.ToString() + "分钟";
  809. break;
  810. case "s":
  811. if (ts.Days > 0)
  812. {
  813. total += ts.Days * 24 * 60 * 60;
  814. }
  815. if (ts.Hours > 0)
  816. {
  817. total += ts.Hours * 60 * 60;
  818. }
  819. if (ts.Minutes > 0)
  820. {
  821. total += ts.Hours * 60;
  822. }
  823. total += ts.Hours;
  824. result = total.ToString() + "秒";
  825. break;
  826. case "time":
  827. if (ts.Days > 1)
  828. {
  829. result = s.ToString("yyyy-MM-dd");
  830. }
  831. else
  832. {
  833. if (ts.Days > 0)
  834. {
  835. result += ts.Days + "天";
  836. }
  837. if (ts.Hours > 0)
  838. {
  839. result += ts.Hours + "小时";
  840. }
  841. if (ts.Minutes > 0)
  842. {
  843. result += ts.Minutes + "分钟";
  844. }
  845. if (string.IsNullOrEmpty(result))
  846. {
  847. result = "刚刚";
  848. }
  849. else
  850. {
  851. result += "前";
  852. }
  853. }
  854. break;
  855. default: break;
  856. }
  857. }
  858. return result;
  859. }
  860. // 半角转全角
  861. public static string ToSBC(string input)
  862. {
  863. char[] c = input.ToCharArray();
  864. for (int i = 0; i < c.Length; i++)
  865. {
  866. if (c[i] == 32)
  867. {
  868. c[i] = (char)12288;
  869. continue;
  870. }
  871. if (c[i] < 127)
  872. c[i] = (char)(c[i] + 65248);
  873. }
  874. return new string(c);
  875. }
  876. // 全角转半角
  877. public static string ToDBC(string input)
  878. {
  879. char[] c = input.ToCharArray();
  880. for (int i = 0; i < c.Length; i++)
  881. {
  882. if (c[i] == 12288)
  883. {
  884. c[i] = (char)32;
  885. continue;
  886. }
  887. if (c[i] > 65280 && c[i] < 65375)
  888. c[i] = (char)(c[i] - 65248);
  889. }
  890. return new string(c);
  891. }
  892. public static string PostWebRequest(string postUrl, string paramData, string ContentType = "application/x-www-form-urlencoded")
  893. {
  894. //return PostWebRequest(postUrl, paramData, new Dictionary<string, string>());
  895. string ret = string.Empty;
  896. try
  897. {
  898. byte[] postData = Encoding.UTF8.GetBytes(paramData);
  899. // 设置提交的相关参数
  900. HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
  901. Encoding myEncoding = Encoding.UTF8;
  902. request.Method = "POST";
  903. request.KeepAlive = false;
  904. request.AllowAutoRedirect = true;
  905. request.ContentType = ContentType;
  906. //request.ContentType = "multipart/form-data; boundary=" + boundary;
  907. 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)";
  908. request.ContentLength = postData.Length;
  909. // 提交请求数据
  910. System.IO.Stream outputStream = request.GetRequestStream();
  911. outputStream.Write(postData, 0, postData.Length);
  912. outputStream.Close();
  913. HttpWebResponse response;
  914. Stream responseStream;
  915. StreamReader reader;
  916. string srcString;
  917. response = request.GetResponse() as HttpWebResponse;
  918. responseStream = response.GetResponseStream();
  919. reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
  920. srcString = reader.ReadToEnd();
  921. ret = srcString; //返回值赋值
  922. reader.Close();
  923. }
  924. catch (Exception ex)
  925. {
  926. ret = "fail";
  927. WriteLog(ex.ToString(), "PostWebRequest");
  928. }
  929. return ret;
  930. }
  931. public static string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> header, string ContentType = "application/x-www-form-urlencoded")
  932. {
  933. //return PostWebRequest(postUrl, paramData, new Dictionary<string, string>());
  934. string ret = string.Empty;
  935. try
  936. {
  937. byte[] postData = Encoding.UTF8.GetBytes(paramData);
  938. // 设置提交的相关参数
  939. HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
  940. Encoding myEncoding = Encoding.UTF8;
  941. request.Method = "POST";
  942. request.KeepAlive = false;
  943. request.AllowAutoRedirect = true;
  944. request.ContentType = ContentType;
  945. //request.ContentType = "multipart/form-data; boundary=" + boundary;
  946. 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)";
  947. request.ContentLength = postData.Length;
  948. if (header.Count > 0)
  949. {
  950. foreach (string key in header.Keys)
  951. {
  952. request.Headers.Add(key, header[key]);
  953. }
  954. }
  955. // 提交请求数据
  956. System.IO.Stream outputStream = request.GetRequestStream();
  957. outputStream.Write(postData, 0, postData.Length);
  958. outputStream.Close();
  959. HttpWebResponse response;
  960. Stream responseStream;
  961. StreamReader reader;
  962. string srcString;
  963. response = request.GetResponse() as HttpWebResponse;
  964. responseStream = response.GetResponseStream();
  965. reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
  966. srcString = reader.ReadToEnd();
  967. ret = srcString; //返回值赋值
  968. reader.Close();
  969. }
  970. catch (Exception ex)
  971. {
  972. ret = "fail";
  973. WriteLog(ex.ToString(), "PostWebRequest");
  974. }
  975. return ret;
  976. }
  977. /// <summary>
  978. /// 从ftp服务器上获得文件夹列表
  979. /// </summary>
  980. /// <param name="RequedstPath">服务器下的相对路径</param>
  981. /// <returns></returns>
  982. public static List<string> GetFtpDirctoryList(string path, string username, string password)
  983. {
  984. List<string> strs = new List<string>();
  985. try
  986. {
  987. string uri = path; //目标路径 path为服务器地址
  988. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  989. // ftp用户名和密码
  990. reqFTP.Credentials = new NetworkCredential(username, password);
  991. reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  992. WebResponse response = reqFTP.GetResponse();
  993. StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
  994. string line = reader.ReadLine();
  995. while (line != null)
  996. {
  997. if (line.Contains("<DIR>"))
  998. {
  999. string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
  1000. strs.Add(msg);
  1001. }
  1002. line = reader.ReadLine();
  1003. }
  1004. reader.Close();
  1005. response.Close();
  1006. return strs;
  1007. }
  1008. catch (Exception ex)
  1009. {
  1010. Function.WriteLog(DateTime.Now + ":" + ex.ToString(), "从ftp服务器上获得文件夹列表异常");
  1011. }
  1012. return strs;
  1013. }
  1014. /// <summary>
  1015. /// 从ftp服务器上获得文件列表
  1016. /// </summary>
  1017. /// <param name="RequedstPath">服务器下的相对路径</param>
  1018. /// <returns></returns>
  1019. public static List<string> GetFtpFileList(string path, string username, string password)
  1020. {
  1021. List<string> strs = new List<string>();
  1022. try
  1023. {
  1024. string uri = path; //目标路径 path为服务器地址
  1025. FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  1026. // ftp用户名和密码
  1027. reqFTP.Credentials = new NetworkCredential(username, password);
  1028. reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  1029. WebResponse response = reqFTP.GetResponse();
  1030. StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
  1031. string line = reader.ReadLine();
  1032. while (line != null)
  1033. {
  1034. if (!line.Contains("<DIR>"))
  1035. {
  1036. string msg = line.Substring(39).Trim();
  1037. strs.Add(msg);
  1038. }
  1039. line = reader.ReadLine();
  1040. }
  1041. reader.Close();
  1042. response.Close();
  1043. return strs;
  1044. }
  1045. catch (Exception ex)
  1046. {
  1047. Function.WriteLog(DateTime.Now + ":" + ex.ToString(), "从ftp服务器上获得文件列表异常");
  1048. }
  1049. return strs;
  1050. }
  1051. //从ftp服务器上下载文件
  1052. public static string FtpDownload(string path, string fileName, string username, string password)
  1053. {
  1054. FtpWebRequest reqFTP;
  1055. string savePath = "";
  1056. try
  1057. {
  1058. string filePath = getPath("/FtpDownloadFile/" + fileName);
  1059. FileStream outputStream = new FileStream(filePath, FileMode.Create);
  1060. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + fileName));
  1061. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  1062. reqFTP.UseBinary = true;
  1063. reqFTP.Credentials = new NetworkCredential(username, password);
  1064. reqFTP.UsePassive = false;
  1065. FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
  1066. Stream ftpStream = response.GetResponseStream();
  1067. long cl = response.ContentLength;
  1068. int bufferSize = 2048;
  1069. int readCount;
  1070. byte[] buffer = new byte[bufferSize];
  1071. readCount = ftpStream.Read(buffer, 0, bufferSize);
  1072. while (readCount > 0)
  1073. {
  1074. outputStream.Write(buffer, 0, readCount);
  1075. readCount = ftpStream.Read(buffer, 0, bufferSize);
  1076. }
  1077. ftpStream.Close();
  1078. outputStream.Close();
  1079. response.Close();
  1080. savePath = "/FtpDownloadFile/" + fileName;
  1081. }
  1082. catch (Exception ex)
  1083. {
  1084. Function.WriteLog(DateTime.Now + ":" + ex.ToString(), "从ftp服务器上下载文件异常");
  1085. }
  1086. return savePath;
  1087. }
  1088. public static string base64StringToImage(string base64String, string path, string filename)
  1089. {
  1090. string fullpath = getPath(path);
  1091. if (!System.IO.Directory.Exists(fullpath))
  1092. {
  1093. System.IO.Directory.CreateDirectory(fullpath);
  1094. }
  1095. byte[] arr = Convert.FromBase64String(base64String);
  1096. System.IO.File.WriteAllBytes(fullpath + filename, arr);
  1097. return path + filename;
  1098. }
  1099. public static String BuildQueryString(SortedList<String, String> kvp)
  1100. {
  1101. return String.Join("&", kvp.Select(item => String.Format("{0}={1}", item.Key.Trim(), item.Value)).ToArray());
  1102. }
  1103. #region 获取网络文件内容
  1104. public static string GetNetFileContent(string url)
  1105. {
  1106. string textContent = "";
  1107. using (var client = new WebClient())
  1108. {
  1109. try
  1110. {
  1111. textContent = client.DownloadString(url); // 通过 DownloadString 方法获取网页内容
  1112. }
  1113. catch (Exception ex)
  1114. {
  1115. WriteLog(DateTime.Now.ToString() + "\n" + url + "\n" + ex.ToString() + "\n\n", "获取网络文件内容异常");
  1116. }
  1117. }
  1118. return textContent;
  1119. }
  1120. public static byte[] GetNetFileData(string url)
  1121. {
  1122. byte[] textContent = new byte[] { };
  1123. using (var client = new WebClient())
  1124. {
  1125. try
  1126. {
  1127. textContent = client.DownloadData(url); // 通过 DownloadString 方法获取网页内容
  1128. }
  1129. catch (Exception ex)
  1130. {
  1131. WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "获取网络文件流异常");
  1132. }
  1133. }
  1134. return textContent;
  1135. }
  1136. #endregion
  1137. }
  1138. }