123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.Diagnostics;
- using System.IO;
- using System.Net;
- using System.Net.Mail;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Web;
- using Microsoft.VisualBasic;
- namespace CB.Common
- {
- public class Utils
- {
- /// <summary>
- /// 记录日志
- /// </summary>
- /// <param name="msg"></param>
- public static void WriteLog(string msg)
- {
- string path = AppDomain.CurrentDomain.BaseDirectory + "\\Log.txt";
- using (StreamWriter sw = new StreamWriter(path, true))
- {
- sw.WriteLine(System.DateTime.Now.ToString() + " " + msg);
- sw.Close();
- }
- }
- #region Post With Pic
- /// <summary>
- /// HTTP POST方式请求数据(带图片)
- /// </summary>
- /// <param name="url">URL</param>
- /// <param name="param">POST的数据</param>
- /// <param name="fileByte">图片</param>
- /// <returns></returns>
- public static string HttpPost(string url, Dictionary<string, object> param, byte[] fileByte)
- {
- string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
- byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
- HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
- wr.ContentType = "multipart/form-data; boundary=" + boundary;
- wr.Method = "POST";
- wr.KeepAlive = true;
- wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
- Stream rs = wr.GetRequestStream();
- string responseStr = null;
- string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
- foreach (string key in param.Keys)
- {
- rs.Write(boundarybytes, 0, boundarybytes.Length);
- string formitem = string.Format(formdataTemplate, key, param[key]);
- byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
- rs.Write(formitembytes, 0, formitembytes.Length);
- }
- rs.Write(boundarybytes, 0, boundarybytes.Length);
- string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
- string header = string.Format(headerTemplate, "pic", fileByte, "text/plain");
- byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
- rs.Write(headerbytes, 0, headerbytes.Length);
- rs.Write(fileByte, 0, fileByte.Length);
- byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
- rs.Write(trailer, 0, trailer.Length);
- rs.Close();
- WebResponse wresp = null;
- try
- {
- wresp = wr.GetResponse();
- Stream stream2 = wresp.GetResponseStream();
- StreamReader reader2 = new StreamReader(stream2);
- responseStr = reader2.ReadToEnd();
- }
- catch
- {
- throw;
- }
- finally
- {
- if (wresp != null)
- {
- wresp.Close();
- wresp = null;
- }
- wr = null;
- }
- return responseStr;
- }
- /// <summary>
- /// http POST请求url
- /// </summary>
- /// <param name="url">请求地址</param>
- /// <param name="postData">POST数据</param>
- /// <returns></returns>
- public static string GetHttpWebResponse(string url, string postData)
- {
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
- request.Method = "POST";
- request.ContentType = "application/x-www-form-urlencoded";
- request.ContentLength = postData.Length;
- request.Timeout = 10000;
- HttpWebResponse response = null;
- try
- {
- StreamWriter swRequestWriter = new StreamWriter(request.GetRequestStream());
- swRequestWriter.Write(postData);
- if (swRequestWriter != null)
- swRequestWriter.Close();
- response = (HttpWebResponse)request.GetResponse();
- using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
- {
- return reader.ReadToEnd();
- }
- }
- catch { return ""; }
- finally
- {
- if (response != null)
- response.Close();
- }
- }
- #endregion
- /// <summary>
- /// AppSetting 配置节点值
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static string GetAppSeting(string key)
- {
- try
- { return new System.Configuration.AppSettingsReader().GetValue(key, typeof(string)).ToString(); }
- catch
- { return string.Empty; }
- }
- /// <summary>
- /// 返回字串长度
- /// 汉字=2
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static int GetStringLength(string str)
- {
- return Encoding.Default.GetBytes(str).Length;
- }
- /// <summary>
- /// 取指定长度的字符串
- /// </summary>
- /// <param name="p_SrcString">要检查的字符串</param>
- /// <param name="p_StartIndex">起始位置</param>
- /// <param name="p_Length">指定长度</param>
- /// <param name="p_TailString">用于替换的字符串</param>
- /// <returns>截取后的字符串</returns>
- public static string GetSubString(string SrcString, int maxLength, string replaceStr = "")
- {
- string myResult = SrcString;
- if (0 >= maxLength)
- return myResult;
- byte[] bsSrcString = Encoding.Default.GetBytes(myResult);
- if (maxLength >= bsSrcString.Length)
- return myResult;
- int p_EndIndex = maxLength;
- int nRealLength = p_EndIndex;
- int[] anResultFlag = new int[p_EndIndex];
- byte[] bsResult = null;
- int nFlag = 0;
- for (int i = 0; i < p_EndIndex; i++)
- {
- if (bsSrcString[i] > 127)
- {
- nFlag++;
- if (nFlag == 3)
- nFlag = 1;
- }
- else
- nFlag = 0;
- anResultFlag[i] = nFlag;
- }
- if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_EndIndex - 1] == 1))
- nRealLength = p_EndIndex + 1;
- bsResult = new byte[nRealLength];
- Array.Copy(bsSrcString, 0, bsResult, 0, nRealLength);
- myResult = Encoding.Default.GetString(bsResult);
- return myResult + replaceStr;
- }
- /// <summary>
- /// 网站域名
- /// </summary>
- /// <returns></returns>
- public static string GetHostDomain()
- {
- return GetUrlDomainName(HttpContext.Current.Request.Url.AbsoluteUri);
- }
- /// <summary>
- /// 返回url的根域名
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string GetUrlDomainName(string url)
- {
- string p = @"^https?://(?<domain>[^/]+)(/|$)";
- Regex reg = new Regex(p, RegexOptions.IgnoreCase);
- Match m = reg.Match(url);
- return m.Groups["domain"].Value.ToString().Trim();
- }
- /// <summary>
- /// 返回URL中结尾的文件名
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string GetUrlFileName(string url)
- {
- if (string.IsNullOrEmpty(url))
- return "";
- string[] str = url.Split('/');
- return str[str.Length - 1].Split('?')[0];
- }
- /// <summary>
- /// 根据字符长度,返回n个*号
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string GetStar(string str)
- {
- int len = str.Length;
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < len; i++)
- {
- sb.Append("*");
- }
- return sb.ToString();
- }
- /// <summary>
- /// 将IP地址转为整数形式
- /// </summary>
- /// <returns>整数</returns>
- public static long IP2Long(IPAddress ip)
- {
- int x = 3;
- long o = 0;
- foreach (byte f in ip.GetAddressBytes())
- {
- o += (long)f << 8 * x--;
- }
- return o;
- }
- /// <summary>
- /// 将整数转为IP地址
- /// </summary>
- /// <returns>IP地址</returns>
- public static IPAddress Long2IP(long l)
- {
- byte[] b = new byte[4];
- for (int i = 0; i < 4; i++)
- {
- b[3 - i] = (byte)(l >> 8 * i & 255);
- }
- return new IPAddress(b);
- }
- /// <summary>
- /// 生成4位数字随机数
- /// </summary>
- /// <returns></returns>
- public static string GetRandomInt()
- {
- Random random = new Random();
- return (random.Next(1000, 9999).ToString());
- }
- /// <summary>
- /// MD5函数
- /// 返回32位大写结果.
- /// </summary>
- /// <param name="str">原始字符串</param>
- /// <returns>MD5结果</returns>
- public static string MD5(string str)
- {
- byte[] b = Encoding.UTF8.GetBytes(str);
- b = new MD5CryptoServiceProvider().ComputeHash(b);
- string ret = "";
- for (int i = 0; i < b.Length; i++)
- ret += b[i].ToString("x").PadLeft(2, '0');
- return ret.ToUpper();
- }
- /// <summary>
- /// 检测是否符合email格式
- /// </summary>
- /// <param name="strEmail">要判断的email字符串</param>
- /// <returns>判断结果</returns>
- public static bool IsValidEmail(string strEmail)
- {
- return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]");
- }
- /// <summary>
- /// 是否为ip
- /// </summary>
- /// <param name="ip"></param>
- /// <returns></returns>
- public static bool IsIP(string ip)
- {
- return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
- }
- /// <summary>
- /// 获得当前页面客户端的IP
- /// </summary>
- /// <returns>当前页面客户端的IP</returns>
- public static string GetRealIP()
- {
- string result = HttpContext.Current.Request.Headers["Cdn-Src-Ip"];//网宿CDN 获取用户IP
- if (string.IsNullOrEmpty(result))
- {
- result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
- }
- if (string.IsNullOrEmpty(result))
- { result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; }
- if (string.IsNullOrEmpty(result))
- { result = HttpContext.Current.Request.UserHostAddress; }
- if (string.IsNullOrEmpty(result) || !IsIP(result))
- { return "127.0.0.1"; }
- return result;
- }
- /// <summary>
- /// 写cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="strValue">值</param>
- /// <param name="strValue">过期时间(分钟)</param>
- public static void WriteCookie(string strName, string strValue, int expires = 480)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie.Value = HttpContext.Current.Server.UrlEncode(strValue);
- cookie.Expires = DateTime.Now.AddMinutes(expires);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 写Cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <param name="key">键</param>
- /// <param name="strValue">值</param>
- /// <param name="expires">过期时间</param>
- public static void WriteCookie(string strName, string key, string strValue, int expires = 480)
- {
- HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
- if (cookie == null)
- {
- cookie = new HttpCookie(strName);
- }
- cookie[key] = HttpContext.Current.Server.UrlEncode(strValue);
- cookie.Expires = DateTime.Now.AddMinutes(expires);
- HttpContext.Current.Response.AppendCookie(cookie);
- }
- /// <summary>
- /// 读cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <returns>cookie值</returns>
- public static string GetCookie(string strName)
- {
- if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
- return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
- return "";
- }
- /// <summary>
- /// 读cookie值
- /// </summary>
- /// <param name="strName">名称</param>
- /// <returns>cookie值</returns>
- public static string GetCookie(string strName, string key)
- {
- if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
- return HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());
- return "";
- }
- /// <summary>
- /// 另外一个清理所有Cookie的方法
- /// </summary>
- public static void FlushAllCookie()
- {
- for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
- {
- HttpContext.Current.Response.Cookies[HttpContext.Current.Request.Cookies.Keys[i]].Expires = DateTime.Now.AddDays(-600);
- HttpContext.Current.Response.Cookies[HttpContext.Current.Request.Cookies.Keys[i]].Values.Clear();
- }
- }
- /// <summary>
- /// 移除Cookies
- /// </summary>
- /// <param name="cookiesName"></param>
- public static void RemoveCookies(string cookiesName)
- {
- if (string.IsNullOrEmpty(cookiesName))
- return;
- HttpCookie cookies = HttpContext.Current.Request.Cookies[cookiesName];
- if (null != cookies)
- {
- HttpContext.Current.Response.Cookies[cookiesName].Expires = DateTime.Now.AddDays(-600);
- HttpContext.Current.Response.Cookies[cookiesName].Values.Clear();
- }
- }
- /// <summary>
- /// 将全角数字转换为数字
- /// </summary>
- /// <param name="SBCCase"></param>
- /// <returns></returns>
- public static string SBCCaseToNumberic(string SBCCase)
- {
- char[] c = SBCCase.ToCharArray();
- for (int i = 0; i < c.Length; i++)
- {
- byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
- if (b.Length == 2)
- {
- if (b[1] == 255)
- {
- b[0] = (byte)(b[0] + 32);
- b[1] = 0;
- c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
- }
- }
- }
- return new string(c);
- }
- /// <summary>
- /// 移除转义字符 如
- /// </summary>
- /// <param name="content"></param>
- /// <returns></returns>
- public static string RemoveEscapeCharacter(string content)
- {
- if (string.IsNullOrEmpty(content))
- return "";
- return Regex.Replace(content, @"&[a-zA-Z]+?;", "", RegexOptions.IgnoreCase);
- }
- /// <summary>
- /// 移除Html标记
- /// </summary>
- /// <param name="content"></param>
- /// <returns></returns>
- public static string RemoveHtml(string content)
- {
- if (string.IsNullOrEmpty(content))
- return "";
- return Regex.Replace(content, @"<[^>]*>", "", RegexOptions.IgnoreCase);
- }
- /// <summary>
- /// 移除空白 换行 TAB 中文空白
- /// </summary>
- /// <param name="content"></param>
- /// <returns></returns>
- public static string RemoveSpacing(string content)
- {
- if (string.IsNullOrEmpty(content))
- return "";
- return Regex.Replace(content, @"\s", "", RegexOptions.IgnoreCase);
- }
- /// <summary>
- /// 检测是否有Sql危险字符
- /// </summary>
- /// <param name="str">要判断字符串</param>
- /// <returns>判断结果</returns>
- public static bool IsSafeSqlString(string str)
- {
- return Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
- }
- /// <summary>
- /// 检测字符号是否只包括数字、字母和中文
- /// </summary>
- /// <param name="str">要判断字符串</param>
- /// <returns>判断结果</returns>
- public static bool IsSafeUserInfoString(string str)
- {
- return Regex.IsMatch(str, "[\\s\\p{P}\n\r=<>$>+¥^]");
- }
- /// <summary>
- /// 判断是否为base64字符串
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static bool IsBase64String(string str)
- {
- //A-Z, a-z, 0-9, +, /, =
- return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]");
- }
- /// <summary>
- /// 判断对象是否为Int32类型的数字
- /// </summary>
- /// <param name="Expression"></param>
- /// <returns></returns>
- public static bool IsNumeric(object Expression)
- {
- return Validator.IsNumeric(Expression);
- }
- /// <summary>
- /// 从HTML中获取文本,保留br,p,img
- /// </summary>
- /// <param name="HTML"></param>
- /// <returns></returns>
- public static string GetTextFromHTML(string HTML)
- {
- System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"</?(?!br|/?p|img)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- return regEx.Replace(HTML, "");
- }
- /// <summary>
- /// 从HTML中获取文本,保留tr,td,strong,br,span,p
- /// </summary>
- /// <param name="HTML"></param>
- /// <returns></returns>
- public static string GetValueFromHTML(string HTML)
- {
- System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"<(table|/table|tbody|/tbody)>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
- return regEx.Replace(HTML, "");
- }
- public static bool IsDouble(object Expression)
- {
- return Validator.IsDouble(Expression);
- }
- /// <summary>
- /// object型转换为bool型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的bool类型结果</returns>
- public static bool ObjectToBool(object expression, bool defValue)
- {
- return TypeConverter.ObjectToBool(expression, defValue);
- }
- /// <summary>
- /// string型转换为bool型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的bool类型结果</returns>
- public static bool StrToBool(string expression, bool defValue)
- {
- return TypeConverter.StrToBool(expression, defValue);
- }
- /// <summary>
- /// 将对象转换为Int32类型
- /// </summary>
- /// <param name="expression">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static int StrToInt(object expression, int defValue)
- {
- return TypeConverter.ObjectToInt(expression, defValue);
- }
- /// <summary>
- /// 将字符串转换为Int32类型
- /// </summary>
- /// <param name="expression">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static int StrToInt(string expression, int defValue)
- {
- return TypeConverter.StrToInt(expression, defValue);
- }
- /// <summary>
- /// 将字符串转换为DateTime类型
- /// </summary>
- /// <param name="expression">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的DateTime类型结果</returns>
- public static DateTime StrToDateTime(string expression, DateTime defValue)
- {
- return TypeConverter.StrToDateTime(expression, defValue);
- }
- /// <summary>
- /// Object型转换为float型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static float StrToFloat(object strValue, float defValue)
- {
- return TypeConverter.StrToFloat(strValue, defValue);
- }
- /// <summary>
- /// string型转换为float型
- /// </summary>
- /// <param name="strValue">要转换的字符串</param>
- /// <param name="defValue">缺省值</param>
- /// <returns>转换后的int类型结果</returns>
- public static float StrToFloat(string strValue, float defValue)
- {
- return TypeConverter.StrToFloat(strValue, defValue);
- }
- /// <summary>
- /// 判断给定的字符串数组(strNumber)中的数据是不是都为数值型
- /// </summary>
- /// <param name="strNumber">要确认的字符串数组</param>
- /// <returns>是则返加true 不是则返回 false</returns>
- public static bool IsNumericArray(string[] strNumber)
- {
- return Validator.IsNumericArray(strNumber);
- }
- /// <summary>
- /// 得到距离开奖的时间差
- /// </summary>
- /// <param name="nowtime">现在时间</param>
- /// <param name="kjtime">开奖时间</param>
- /// <param name="days">过期时间 增加的天数</param>
- /// <returns>时间差</returns>
- public static TimeSpan KjTimeDiff(DateTime nowtime, DateTime kjtime)
- {
- TimeSpan ts = new TimeSpan();
- if (kjtime > nowtime)
- {
- TimeSpan ts1 = new TimeSpan(nowtime.Ticks);
- TimeSpan ts2 = new TimeSpan(kjtime.Ticks);
- ts = ts1.Subtract(ts2).Duration();
- }
- else
- {
- TimeSpan ts1 = new TimeSpan(nowtime.Ticks);
- TimeSpan ts2 = new TimeSpan(nowtime.Ticks);
- ts = ts1.Subtract(ts2).Duration();
- }
- return ts;
- }
- public static string GetLoadTitle(string title)
- {
- if (title.Length > 20)
- {
- title = title.Substring(0, 17).PadRight(20, '.');
- }
- return title;
- }
- /// <summary>
- /// 取页面源码
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string GetPagehtml(string url)
- {
- try
- {
- WebRequest request = WebRequest.Create(url);
- request.Timeout = 20000;//20秒超时
- WebResponse response = request.GetResponse();
- Stream resStream = response.GetResponseStream();
- StreamReader sr = new StreamReader(resStream);
- return sr.ReadToEnd();
- }
- catch { return ""; }
- }
- }
- }
|