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 } }