1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246 |
- using System;
- using System.Data;
- using System.Web;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Net.Mail;
- using System.Net;
- using LitJson;
- using Microsoft.AspNetCore.Http;
- using ThoughtWorks.QRCode.Codec;
- using System.Linq;
- using System.IO;
- using SkiaSharp.QrCode;
- using SkiaSharp;
- namespace Common
- {
- public class Function
- {
- /// <summary>
- /// hmacSha1算法加密(生成长度40)
- /// </summary>
- /// <param name="encryptText">加密明文</param>
- /// <param name="encryptKey">加密密钥</param>
- /// <returns></returns>
- public static string hmacSha1(string encryptText, string encryptKey)
- {
- HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(encryptKey));
- byte[] RstRes = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(encryptText));
- StringBuilder EnText = new StringBuilder();
- foreach (byte Byte in RstRes)
- {
- EnText.AppendFormat("{0:x2}", Byte);
- }
- return EnText.ToString();
- }
- public static string hmacmd5(string encryptText, string encryptKey)
- {
- HMACMD5 myHMACSHA1 = new HMACMD5(Encoding.UTF8.GetBytes(encryptKey));
- byte[] RstRes = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(encryptText));
- StringBuilder EnText = new StringBuilder();
- foreach (byte Byte in RstRes)
- {
- EnText.AppendFormat("{0:x2}", Byte);
- }
- return EnText.ToString();
- }
- /// <summary>
- /// MD5 32位加密字符串
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string MD5_32(string str)
- {
- string cl = str + "@$1212#";
- string pwd = "";
- MD5 md5 = MD5.Create();//实例化一个md5对像
- // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
- byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
- // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
- for (int i = 0; i < s.Length; i++)
- {
- // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
- pwd = pwd + s[i].ToString("X").ToLower().PadLeft(2, '0');
- }
- return pwd;
- }
- public static string MD532(string str)
- {
- string cl = str;
- string pwd = "";
- MD5 md5 = MD5.Create();//实例化一个md5对像
- // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
- byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
- // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
- for (int i = 0; i < s.Length; i++)
- {
- // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
- pwd = pwd + s[i].ToString("X").ToLower().PadLeft(2, '0');
- }
- return pwd;
- }
- /// <summary>
- /// 获取MD5值
- /// </summary>
- /// <param name="str">加密的字符串</param>
- /// <returns>返回MD5值</returns>
- public static string MD5_16(string str)
- {
- return MD5_32(str).Substring(8, 16);
- }
- /// <summary>
- /// 写日志(错误报告)
- /// </summary>
- /// <param name="str"></param>
- public static void WriteLog(string str)
- {
- try
- {
- string path = getPath("/log/message/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/");
- if (!Directory.Exists(path))
- {
- Directory.CreateDirectory(path);
- }
- StreamWriter sw = File.AppendText(path + "content.log");
- sw.WriteLine(str);
- sw.Flush();
- sw.Dispose();
- }
- catch
- { }
- }
- /// <summary>
- /// 写日志(错误报告)
- /// </summary>
- /// <param name="str"></param>
- public static void WriteLog(string str, string filename)
- {
- try
- {
- string path = getPath("/log/" + filename + "/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Day.ToString() + "/");
- if (!Directory.Exists(path))
- {
- Directory.CreateDirectory(path);
- }
- StreamWriter sw = File.AppendText(path + "content.log");
- sw.WriteLine(str);
- sw.Flush();
- sw.Dispose();
- }
- catch
- { }
- }
- public static void WriteLog(string path_str, string file_name, string page_content)
- {
- try
- {
- string path = getPath(path_str);
- if (!Directory.Exists(path))
- {
- Directory.CreateDirectory(path);
- }
- StreamWriter sw = File.AppendText(path + "/" + file_name);
- sw.WriteLine(page_content);
- sw.Flush();
- sw.Dispose();
- }
- catch
- { }
- }
- /// <summary>
- /// 过滤html代码
- /// </summary>
- /// <param name="Htmlstring"></param>
- public static string NoHTML(string Htmlstring) //去除HTML标记
- {
- if (Htmlstring == null || Htmlstring == string.Empty)
- {
- return "";
- }
- Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
- //Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
- Htmlstring = Regex.Replace(Htmlstring, @"&.*?;", "", RegexOptions.IgnoreCase);
- Htmlstring = Htmlstring.Replace("<", "〈");
- Htmlstring = Htmlstring.Replace(">", "〉");
- //Htmlstring = Htmlstring.Replace("\r\n", "");
- //Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
- return Htmlstring;
- }
- public static bool IsIncludeChinese(string str)
- {
- Regex r = new Regex(@"[\u4E00-\u9FA5]", RegexOptions.IgnoreCase);
- if (r.IsMatch(str))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- public static bool IsInt(string numberString)
- {
- if (string.IsNullOrEmpty(numberString))
- {
- return false;
- }
- Regex rCode = new Regex("^\\d+$");
- if (!rCode.IsMatch(numberString))
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- public static string CheckInt(string numberString)
- {
- if (string.IsNullOrEmpty(numberString))
- {
- return "0";
- }
- Regex rCode = new Regex("^\\d+$");
- if (!rCode.IsMatch(numberString))
- {
- return "0";
- }
- else
- {
- return numberString;
- }
- }
- public static DateTime CheckDateTime(string numberString)
- {
- if (string.IsNullOrEmpty(numberString))
- {
- return DateTime.Now;
- }
- DateTime result;
- if (DateTime.TryParse(numberString, out result))
- {
- return result;
- }
- else
- {
- return DateTime.Now;
- }
- }
- public static bool ChkDateTime(string numberString)
- {
- if (string.IsNullOrEmpty(numberString))
- {
- return false;
- }
- DateTime result;
- if (DateTime.TryParse(numberString, out result))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- public static string CheckNull(string numberString)
- {
- if (string.IsNullOrEmpty(numberString))
- {
- return "";
- }
- else
- {
- return numberString;
- }
- }
- public static string CheckUrl(string str)
- {
- if (str == null || str == string.Empty)
- {
- return "";
- }
- 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\&%_\./-~-]*)?");
- if (!rCode.IsMatch(str))
- {
- return "";
- }
- else
- {
- return str;
- }
- }
- public static string CheckEmail(string str)
- {
- if (str == null || str == string.Empty)
- {
- return "";
- }
- Regex rCode = new Regex(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
- if (!rCode.IsMatch(str))
- {
- return "";
- }
- else
- {
- return str;
- }
- }
- public static string CheckMobile(string str)
- {
- if (str == null || str == string.Empty)
- {
- return "";
- }
- Regex rCode = new Regex(@"^1[3456789]\d{9}$");
- if (!rCode.IsMatch(str))
- {
- return "";
- }
- else
- {
- return str;
- }
- }
- public static string CheckIdCard(string str)
- {
- if (str == null || str == string.Empty)
- {
- return "";
- }
- 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)$");
- if (!rCode.IsMatch(str))
- {
- return "";
- }
- else
- {
- return str;
- }
- }
- public static bool IsNum(string numberString)
- {
- if (string.IsNullOrEmpty(numberString))
- {
- return false;
- }
- Regex rCode = new Regex(@"^\d+(\.\d+)?$");
- if (!rCode.IsMatch(numberString))
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- public static string CheckNum(string numberString)
- {
- if (string.IsNullOrEmpty(numberString))
- {
- return "0";
- }
- Regex rCode = new Regex(@"^\d+(\.\d+)?$");
- if (!rCode.IsMatch(numberString))
- {
- return "0";
- }
- else
- {
- return numberString;
- }
- }
- public static string CheckString(string str)
- {
- if (string.IsNullOrEmpty(str))
- {
- return "";
- }
- str = str.Replace("'", "´");
- str = str.Replace("\"", """);
- //str = str.Replace(" ", " ");
- str = str.Replace("<", "<");
- str = str.Replace(">", ">");
- str = str.Replace("(", "(");
- str = str.Replace(")", ")");
- str = ToDBC(str);
- return str;
- }
- public static string unCheckString(string str)
- {
- if (str == null || str == string.Empty)
- {
- return "";
- }
- str = str.Replace("´", "'");
- str = str.Replace(""", "\"");
- //str = str.Replace(" ", " ");
- str = str.Replace("<", "<");
- str = str.Replace(">", ">");
- str = str.Replace("(", "(");
- str = str.Replace(")", ")");
- return str;
- }
- public static string CheckString2(string str)
- {
- if (str == null || str == string.Empty)
- {
- return "";
- }
- str = ToDBC(str);
- str = Regex.Replace(str, @"<script.*?>[\s\S]*?</script>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<script.*?>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<object.*?>[\s\S]*?</object>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<object.*?>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<iframe.*?>[\s\S]*?</iframe>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<frameset.*?>[\s\S]*?</frameset>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<frameset.*?>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<frame.*?>[\s\S]*?</frame>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<frame.*?>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<form.*?>[\s\S]*?</form>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<input.*?>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<select.*?>[\s\S]*?</select>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<textarea.*?>[\s\S]*?</textarea>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<button.*?>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<noframes.*?>[\s\S]*?</noframes>", "", RegexOptions.IgnoreCase);
- str = Regex.Replace(str, @"<noframes.*?>", "", RegexOptions.IgnoreCase);
- return str;
- }
- public static string GetSession(HttpContext context, string strName)
- {
- var value = context.Session.GetString(strName);
- if (string.IsNullOrEmpty(value))
- {
- value = "";
- }
- return value;
- }
- public static void WriteSession(HttpContext context, string strName, string strValue)
- {
- context.Session.SetString(strName, strValue);
- }
- public static void DelSession(HttpContext context, string strName)
- {
- context.Session.Remove(strName);
- }
- public static string rootIndex = System.AppDomain.CurrentDomain.BaseDirectory;
- private static string Read(string absoluteFileLocation)
- {
- string result = "";
- if (System.IO.File.Exists(absoluteFileLocation))
- {
- using (FileStream fs = new FileStream(absoluteFileLocation, FileMode.Open, FileAccess.Read))
- {
- using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8))
- {
- try
- {
- result = sr.ReadToEnd();
- //dbconn.InsertCache(absoluteFileLocation, result, 30);
- }
- catch
- { }
- }
- }
- }
- return result;
- }
- public static string getPath(string path_str)
- {
- string result = AppContext.BaseDirectory + path_str;
- return result;
- }
- public static string ReadInstance(string path_str)
- {
- //string path = System.IO.Path.Combine(rootIndex, path_str).Replace('/', System.IO.Path.DirectorySeparatorChar);
- string path = getPath(path_str);
- string content = "";
- content = Read(path);
- return content;
- }
- public static string ReadInstanceNoAuth(string path_str)
- {
- //string path = System.IO.Path.Combine(rootIndex, path_str).Replace('/', System.IO.Path.DirectorySeparatorChar);
- string path = getPath(path_str);
- string content = "";
- content = Read(path);
- return content;
- }
- public static string ReadInstanceByFull(string path_str)
- {
- string content = "";
- content = Read(path_str);
- return content;
- }
- public static void WritePage(string path_str, string file_name, string page_content)
- {
- try
- {
- string path = getPath(path_str);
- if (!Directory.Exists(path))
- {
- Directory.CreateDirectory(path);
- }
- Encoding nobom = new UTF8Encoding(false, false);
- StreamWriter sw = new StreamWriter(path + "/" + file_name, false, nobom);
- sw.Write(page_content);
- sw.Flush();
- sw.Dispose();
- }
- catch
- { }
- }
- public static void WritePageFullPath(string path_str, string file_name, string page_content)
- {
- try
- {
- if (!Directory.Exists(path_str))
- {
- Directory.CreateDirectory(path_str);
- }
- Encoding nobom = new UTF8Encoding(false, false);
- StreamWriter sw = new StreamWriter(path_str + file_name, false, nobom);
- sw.Write(page_content);
- sw.Flush();
- sw.Dispose();
- }
- catch
- { }
- }
- public static void send_email(string mailTitle, string mailTo, string mailContent, string file_path, string host, int port, string username, string pwd, string displayname)
- {
- try
- {
- MailAddress from = new MailAddress(username, displayname); //邮件的发件人
- MailMessage mail = new MailMessage();
- //设置邮件的标题
- mail.Subject = mailTitle;
- mail.SubjectEncoding = Encoding.UTF8;
- //设置邮件的发件人
- //Pass:如果不想显示自己的邮箱地址,这里可以填符合mail格式的任意名称,真正发mail的用户不在这里设定,这个仅仅只做显示用
- mail.From = from;
- //设置邮件的收件人
- string address = "";
- string displayName = "";
- /**/
- /* 这里这样写是因为可能发给多个联系人,每个地址用 ; 号隔开
- 一般从地址簿中直接选择联系人的时候格式都会是 :用户名1 < mail1 >; 用户名2 < mail 2>;
- 因此就有了下面一段逻辑不太好的代码
- 如果永远都只需要发给一个收件人那么就简单了 mail.To.Add("收件人mail");
- */
- string[] mailNames = (mailTo + ";").Split(';');
- foreach (string name in mailNames)
- {
- if (name != string.Empty)
- {
- if (name.IndexOf('<') > 0)
- {
- displayName = name.Substring(0, name.IndexOf('<'));
- address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
- }
- else
- {
- displayName = string.Empty;
- address = name.Substring(name.IndexOf('<') + 1).Replace('>', ' ');
- }
- mail.To.Add(new MailAddress(address, displayName));
- }
- }
- //设置邮件的抄送收件人
- //这个就简单多了,如果不想快点下岗重要文件还是CC一份给领导比较好
- //mail.CC.Add(new MailAddress("Manage@hotmail.com", "尊敬的领导"));
- //设置邮件的内容
- mail.Body = mailContent;
- //设置邮件的格式
- mail.BodyEncoding = Encoding.UTF8;
- mail.IsBodyHtml = true;
- //设置邮件的发送级别
- mail.Priority = MailPriority.Normal;
- //设置邮件的附件,将在客户端选择的附件先上传到服务器保存一个,然后加入到mail中
- //string fileName = file_path;
- //fileName = "D:/UpFile/" + fileName.Substring(fileName.LastIndexOf("/") + 1);
- //txtUpFile.PostedFile.SaveAs(fileName); // 将文件保存至服务器
- //mail.Attachments.Add(new Attachment(fileName));
- mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
- SmtpClient client = new SmtpClient();
- //设置用于 SMTP 事务的主机的名称,填IP地址也可以了
- //client.Host = "smtp.163.com";
- client.Host = host;
- //设置用于 SMTP 事务的端口,默认的是 25
- //client.Port = 25;
- client.Port = port;
- client.UseDefaultCredentials = false;
- client.EnableSsl = true;
- //这里才是真正的邮箱登陆名和密码,比如我的邮箱地址是 hbgx@hotmail, 我的用户名为 hbgx ,我的密码是 xgbh
- client.Credentials = new System.Net.NetworkCredential(username, pwd);
- client.DeliveryMethod = SmtpDeliveryMethod.Network;
- client.Send(mail);
- }
- catch (Exception ex)
- {
- Function.WriteLog(ex.ToString());
- }
- }
- public static string GetWebRequest(string url)
- {
- return GetWebRequest(url, new Dictionary<string, string>());
- }
- public static string GetWebRequest(string url, Dictionary<string, string> header)
- {
- string result = "";
- try
- {
- HttpWebRequest webReq = (HttpWebRequest)HttpWebRequest.Create(url);
- webReq.Method = "GET";
- webReq.KeepAlive = true;
- webReq.Timeout = 1200000;
- webReq.ContentType = "text/html";//application/x-www-form-urlencoded
- if (header.Count > 0)
- {
- foreach (string key in header.Keys)
- {
- webReq.Headers.Add(key, header[key]);
- }
- }
- webReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
- using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
- {
- using (StreamReader reader = new StreamReader(response.GetResponseStream()))
- {
- result = reader.ReadToEnd();
- //function.WriteLog(context.Request.QueryString["mobile"] + " " + reader.ReadToEnd());
- }
- if (response != null)
- response.Close();
- }
- }
- catch (Exception ex)
- {
- result = ex.ToString();
- }
- return result;
- }
- public static string get_Random(int num)
- {
- string[] str = new string[num];
- string serverCode = "";
- //生成随机生成器
- Random random = new Random(GetRandomSeed());
- for (int i = 0; i < num; i++)
- {
- str[i] = random.Next(10).ToString().Substring(0, 1);
- }
- foreach (string s in str)
- {
- serverCode += s;
- }
- return serverCode;
- }
- public static int get_Random(int min, int max)
- {
- int serverCode = 0;
- Random random = new Random(GetRandomSeed());
- serverCode = random.Next(max - min) + min;
- return serverCode;
- }
- public static string get_Random_string(int count)
- {
- string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
- string result = "";
- for (int i = 0; i < count; i++)
- {
- Random r = new Random(GetRandomSeed());
- int serverCode = r.Next(str.Length - 0) + 0;
- result += str.Substring(serverCode, 1);
- }
- return result;
- }
- public static int GetRandomSeed()
- {
- //字节数组,用于存储
- byte[] bytes = new byte[4];
- //创建加密服务,实现加密随机数生成器
- System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
- //加密数据存入字节数组
- rng.GetBytes(bytes);
- //转成整型数据返回,作为随机数生成种子
- return BitConverter.ToInt32(bytes, 0);
- }
- public static string get_weekday(DateTime date)
- {
- string[] week = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
- return week[(int)date.DayOfWeek];
- }
- public static string get_substr(string s, int length)
- {
- byte[] bytes = System.Text.Encoding.Unicode.GetBytes(s);
- int n = 0; // 表示当前的字节数
- int i = 0; // 要截取的字节数
- for (; i < bytes.GetLength(0) && n < length; i++)
- {
- // 偶数位置,如0、2、4等,为UCS2编码中两个字节的第一个字节
- if (i % 2 == 0)
- {
- n++; // 在UCS2第一个字节时n加1
- }
- else
- {
- // 当UCS2编码的第二个字节大于0时,该UCS2字符为汉字,一个汉字算两个字节
- if (bytes[i] > 0)
- {
- n++;
- }
- }
- }
- // 如果i为奇数时,处理成偶数
- if (i % 2 == 1)
- {
- // 该UCS2字符是汉字时,去掉这个截一半的汉字
- if (bytes[i] > 0)
- i = i - 1;
- // 该UCS2字符是字母或数字,则保留该字符
- else
- i = i + 1;
- }
- return System.Text.Encoding.Unicode.GetString(bytes, 0, i);
- }
- public static DateTime ConvertIntDateTime(double d)
- {
- DateTime time = DateTime.MinValue;
- DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
- time = startTime.AddSeconds(d);
- return time;
- }
- public static DateTime ConvertIntDateTimeMini(long TimeStamp)
- {
- System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
- return startTime.AddTicks(TimeStamp * 10000);
- }
- public static int ConvertDateTimeInt(DateTime time)
- {
- double intResult = 0;
- DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
- TimeSpan ts = time - startTime;
- intResult = Math.Round(ts.TotalSeconds, 0);
- return int.Parse(intResult.ToString());
- }
- public static long GetCurTimestamp()
- {
- var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
- long times = Convert.ToInt64(ts.TotalMilliseconds);
- return times;
- }
- public static DateTime checkDateTimeNull(DateTime? datetime)
- {
- if (datetime != null)
- {
- return datetime.Value;
- }
- return DateTime.Now;
- }
- public static bool IsDate(string datetime)
- {
- DateTime check = DateTime.Now;
- return DateTime.TryParse(datetime + " 00:00:00", out check);
- }
- public static bool IsDateTime(string datetime)
- {
- DateTime check = DateTime.Now;
- return DateTime.TryParse(datetime, out check);
- }
- /// <summary>
- /// 获取时间戳
- /// </summary>
- /// <returns></returns>
- public static string getTimeStamp()
- {
- TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
- return Convert.ToInt64(ts.TotalSeconds).ToString();
- }
- public static string get_timespan(DateTime s, string show_type)
- {
- string result = get_timespan(s, DateTime.Now, show_type);
- return result;
- }
- public static string get_timespan(DateTime s, DateTime e, string show_type)
- {
- string result = "";
- if (e > s)
- {
- int total = 0;
- TimeSpan ts = e - s;
- switch (show_type)
- {
- case "d":
- result = ts.Days.ToString() + "天";
- break;
- case "h":
- if (ts.Days > 0)
- {
- total += ts.Days * 24;
- }
- total += ts.Hours;
- result = total.ToString() + "小时";
- break;
- case "m":
- if (ts.Days > 0)
- {
- total += ts.Days * 24 * 60;
- }
- if (ts.Hours > 0)
- {
- total += ts.Hours * 60;
- }
- total += ts.Hours;
- result = total.ToString() + "分钟";
- break;
- case "s":
- if (ts.Days > 0)
- {
- total += ts.Days * 24 * 60 * 60;
- }
- if (ts.Hours > 0)
- {
- total += ts.Hours * 60 * 60;
- }
- if (ts.Minutes > 0)
- {
- total += ts.Hours * 60;
- }
- total += ts.Hours;
- result = total.ToString() + "秒";
- break;
- case "time":
- if (ts.Days > 1)
- {
- result = s.ToString("yyyy-MM-dd");
- }
- else
- {
- if (ts.Days > 0)
- {
- result += ts.Days + "天";
- }
- if (ts.Hours > 0)
- {
- result += ts.Hours + "小时";
- }
- if (ts.Minutes > 0)
- {
- result += ts.Minutes + "分钟";
- }
- if (string.IsNullOrEmpty(result))
- {
- result = "刚刚";
- }
- else
- {
- result += "前";
- }
- }
- break;
- default: break;
- }
- }
- return result;
- }
- // 半角转全角
- public static string ToSBC(string input)
- {
- char[] c = input.ToCharArray();
- for (int i = 0; i < c.Length; i++)
- {
- if (c[i] == 32)
- {
- c[i] = (char)12288;
- continue;
- }
- if (c[i] < 127)
- c[i] = (char)(c[i] + 65248);
- }
- return new string(c);
- }
- // 全角转半角
- public static string ToDBC(string input)
- {
- char[] c = input.ToCharArray();
- for (int i = 0; i < c.Length; i++)
- {
- if (c[i] == 12288)
- {
- c[i] = (char)32;
- continue;
- }
- if (c[i] > 65280 && c[i] < 65375)
- c[i] = (char)(c[i] - 65248);
- }
- return new string(c);
- }
- public static string PostWebRequest(string postUrl, string paramData, string ContentType = "application/x-www-form-urlencoded")
- {
- //return PostWebRequest(postUrl, paramData, new Dictionary<string, string>());
- string ret = string.Empty;
- try
- {
- byte[] postData = Encoding.UTF8.GetBytes(paramData);
- // 设置提交的相关参数
- HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
- Encoding myEncoding = Encoding.UTF8;
- request.Method = "POST";
- request.KeepAlive = false;
- request.AllowAutoRedirect = true;
- request.ContentType = ContentType;
- //request.ContentType = "multipart/form-data; boundary=" + boundary;
- 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)";
- request.ContentLength = postData.Length;
- // 提交请求数据
- System.IO.Stream outputStream = request.GetRequestStream();
- outputStream.Write(postData, 0, postData.Length);
- outputStream.Close();
- HttpWebResponse response;
- Stream responseStream;
- StreamReader reader;
- string srcString;
- response = request.GetResponse() as HttpWebResponse;
- responseStream = response.GetResponseStream();
- reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
- srcString = reader.ReadToEnd();
- ret = srcString; //返回值赋值
- reader.Close();
- }
- catch (Exception ex)
- {
- ret = "fail";
- WriteLog(ex.ToString(), "PostWebRequest");
- }
- return ret;
- }
- public static string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> header, string ContentType = "application/x-www-form-urlencoded")
- {
- //return PostWebRequest(postUrl, paramData, new Dictionary<string, string>());
- string ret = string.Empty;
- try
- {
- byte[] postData = Encoding.UTF8.GetBytes(paramData);
- // 设置提交的相关参数
- HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
- Encoding myEncoding = Encoding.UTF8;
- request.Method = "POST";
- request.KeepAlive = false;
- request.AllowAutoRedirect = true;
- request.ContentType = ContentType;
- //request.ContentType = "multipart/form-data; boundary=" + boundary;
- 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)";
- request.ContentLength = postData.Length;
- if (header.Count > 0)
- {
- foreach (string key in header.Keys)
- {
- request.Headers.Add(key, header[key]);
- }
- }
- // 提交请求数据
- System.IO.Stream outputStream = request.GetRequestStream();
- outputStream.Write(postData, 0, postData.Length);
- outputStream.Close();
- HttpWebResponse response;
- Stream responseStream;
- StreamReader reader;
- string srcString;
- response = request.GetResponse() as HttpWebResponse;
- responseStream = response.GetResponseStream();
- reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
- srcString = reader.ReadToEnd();
- ret = srcString; //返回值赋值
- reader.Close();
- }
- catch (Exception ex)
- {
- ret = "fail";
- WriteLog(ex.ToString(), "PostWebRequest");
- }
- return ret;
- }
- /// <summary>
- /// 从ftp服务器上获得文件夹列表
- /// </summary>
- /// <param name="RequedstPath">服务器下的相对路径</param>
- /// <returns></returns>
- public static List<string> GetFtpDirctoryList(string path, string username, string password)
- {
- List<string> strs = new List<string>();
- try
- {
- string uri = path; //目标路径 path为服务器地址
- FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
- // ftp用户名和密码
- reqFTP.Credentials = new NetworkCredential(username, password);
- reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
- WebResponse response = reqFTP.GetResponse();
- StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
-
- string line = reader.ReadLine();
- while (line != null)
- {
- if (line.Contains("<DIR>"))
- {
- string msg = line.Substring(line.LastIndexOf("<DIR>") + 5).Trim();
- strs.Add(msg);
- }
- line = reader.ReadLine();
- }
- reader.Close();
- response.Close();
- return strs;
- }
- catch (Exception ex)
- {
- Function.WriteLog(DateTime.Now + ":" + ex.ToString(), "从ftp服务器上获得文件夹列表异常");
- }
- return strs;
- }
-
- /// <summary>
- /// 从ftp服务器上获得文件列表
- /// </summary>
- /// <param name="RequedstPath">服务器下的相对路径</param>
- /// <returns></returns>
- public static List<string> GetFtpFileList(string path, string username, string password)
- {
- List<string> strs = new List<string>();
- try
- {
- string uri = path; //目标路径 path为服务器地址
- FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
- // ftp用户名和密码
- reqFTP.Credentials = new NetworkCredential(username, password);
- reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
- WebResponse response = reqFTP.GetResponse();
- StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
-
- string line = reader.ReadLine();
- while (line != null)
- {
- if (!line.Contains("<DIR>"))
- {
- string msg = line.Substring(39).Trim();
- strs.Add(msg);
- }
- line = reader.ReadLine();
- }
- reader.Close();
- response.Close();
- return strs;
- }
- catch (Exception ex)
- {
- Function.WriteLog(DateTime.Now + ":" + ex.ToString(), "从ftp服务器上获得文件列表异常");
- }
- return strs;
- }
- //从ftp服务器上下载文件
- public static string FtpDownload(string path, string fileName, string username, string password)
- {
- FtpWebRequest reqFTP;
- string savePath = "";
- try
- {
- string filePath = getPath("/FtpDownloadFile/" + fileName);
- FileStream outputStream = new FileStream(filePath, FileMode.Create);
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + fileName));
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- reqFTP.UseBinary = true;
- reqFTP.Credentials = new NetworkCredential(username, password);
- reqFTP.UsePassive = false;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- Stream ftpStream = response.GetResponseStream();
- long cl = response.ContentLength;
- int bufferSize = 2048;
- int readCount;
- byte[] buffer = new byte[bufferSize];
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- while (readCount > 0)
- {
- outputStream.Write(buffer, 0, readCount);
- readCount = ftpStream.Read(buffer, 0, bufferSize);
- }
- ftpStream.Close();
- outputStream.Close();
- response.Close();
- savePath = "/FtpDownloadFile/" + fileName;
- }
- catch (Exception ex)
- {
- Function.WriteLog(DateTime.Now + ":" + ex.ToString(), "从ftp服务器上下载文件异常");
- }
- return savePath;
- }
- public static string base64StringToImage(string base64String, string path, string filename)
- {
- string fullpath = getPath(path);
- if (!System.IO.Directory.Exists(fullpath))
- {
- System.IO.Directory.CreateDirectory(fullpath);
- }
- byte[] arr = Convert.FromBase64String(base64String);
- System.IO.File.WriteAllBytes(fullpath + filename, arr);
- return path + filename;
- }
- public static String BuildQueryString(SortedList<String, String> kvp)
- {
- return String.Join("&", kvp.Select(item => String.Format("{0}={1}", item.Key.Trim(), item.Value)).ToArray());
- }
- public static string CreateQRCode2(string content, string name, string myPath, int scale = 600)
- {
- //判断文件路径是否存在,不存在则创建文件夹
- string path = getPath("/" + myPath + "/");
- try
- {
- if (!System.IO.Directory.Exists(path))
- {
- System.IO.Directory.CreateDirectory(path);//不存在就创建目录
- }
- var savePath = path + name + ".png";
- using var generator = new QRCodeGenerator();
- var qr = generator.CreateQrCode(content, ECCLevel.H);
- var info = new SKImageInfo(scale, scale);
- using var surface = SKSurface.Create(info);
- var canvas = surface.Canvas;
- canvas.Render(qr, info.Width, info.Height);
- using var image = surface.Snapshot();
- using var data = image.Encode(SKEncodedImageFormat.Png, 100);
- File.WriteAllBytes(savePath, data.ToArray());
- }
- catch (Exception ex)
- {
- Function.WriteLog(ex.ToString(), "CreateQRCode");
- }
- return "/" + myPath + "/" + name + ".png";
- }
- #region 获取网络文件内容
- public static string GetNetFileContent(string url)
- {
- string textContent = "";
- using (var client = new WebClient())
- {
- try
- {
- textContent = client.DownloadString(url); // 通过 DownloadString 方法获取网页内容
- }
- catch (Exception ex)
- {
- WriteLog(DateTime.Now.ToString() + "\n" + url + "\n" + ex.ToString() + "\n\n", "获取网络文件内容异常");
- }
- }
- return textContent;
- }
- public static byte[] GetNetFileData(string url)
- {
- byte[] textContent = new byte[] { };
- using (var client = new WebClient())
- {
- try
- {
- textContent = client.DownloadData(url); // 通过 DownloadString 方法获取网页内容
- }
- catch (Exception ex)
- {
- WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "获取网络文件流异常");
- }
- }
- return textContent;
- }
- #endregion
- }
- }
|