| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283 |
- 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;
- 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, bool statusCode = false)
- {
- 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();
- if (statusCode)
- {
- result += "|" + response.StatusCode;
- }
- //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", bool statusCode = false)
- {
- //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();
- if (statusCode)
- {
- ret += "|" + response.StatusCode;
- }
- }
- catch (Exception ex)
- {
- ret = "fail";
- WriteLog(ex.ToString(), "PostWebRequest");
- }
- return ret;
- }
- public static string PostWebRequest(string postUrl, string paramData, Dictionary<string, string> header, string Method, string ContentType = "application/x-www-form-urlencoded", bool statusCode = false)
- {
- //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 = Method;
- 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();
- if (statusCode)
- {
- ret += "|" + response.StatusCode;
- }
- }
- catch (Exception ex)
- {
- ret = ex.ToString();
- WriteLog(ex.ToString(), "PostWebRequest");
- }
- return ret;
- }
- public static string DeleteWithBody(string url, string jsonBody, Dictionary<string, string> headers = null, bool statusCode = false)
- {
- try
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.Method = "DELETE";
- request.Timeout = 10000;
- request.ContentType = "application/json;charset=utf-8";
- if (headers != null)
- {
- foreach (var h in headers)
- request.Headers.Add(h.Key, h.Value);
- }
- // 写入json body
- byte[] buffer = System.Text.Encoding.UTF8.GetBytes(jsonBody);
- request.ContentLength = buffer.Length;
- using Stream reqStream = request.GetRequestStream();
- reqStream.Write(buffer, 0, buffer.Length);
- using HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- using StreamReader sr = new StreamReader(response.GetResponseStream());
- string ret = sr.ReadToEnd();
- if (statusCode)
- {
- ret += "|" + response.StatusCode;
- }
- return ret;
- }
- catch (Exception ex)
- {
- return ex.ToString();
- }
- }
- /// <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());
- }
- #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
- public static void DownloadNetFile(string url, string savePath)
- {
- using (var client = new WebClient())
- {
- try
- {
- string dir = savePath.Substring(0, savePath.LastIndexOf("/"));
- if (!System.IO.Directory.Exists(dir))
- {
- System.IO.Directory.CreateDirectory(dir);
- }
- client.DownloadFile(url, savePath); // 通过 DownloadString 方法获取网页内容
- }
- catch (Exception ex)
- {
- WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "下载网络文件异常");
- }
- }
- }
- }
- }
|