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 { /// /// 记录日志 /// /// 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 /// /// HTTP POST方式请求数据(带图片) /// /// URL /// POST的数据 /// 图片 /// public static string HttpPost(string url, Dictionary 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; } /// /// http POST请求url /// /// 请求地址 /// POST数据 /// 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 /// /// AppSetting 配置节点值 /// /// /// public static string GetAppSeting(string key) { try { return new System.Configuration.AppSettingsReader().GetValue(key, typeof(string)).ToString(); } catch { return string.Empty; } } /// /// 返回字串长度 /// 汉字=2 /// /// /// public static int GetStringLength(string str) { return Encoding.Default.GetBytes(str).Length; } /// /// 取指定长度的字符串 /// /// 要检查的字符串 /// 起始位置 /// 指定长度 /// 用于替换的字符串 /// 截取后的字符串 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; } /// /// 网站域名 /// /// public static string GetHostDomain() { return GetUrlDomainName(HttpContext.Current.Request.Url.AbsoluteUri); } /// /// 返回url的根域名 /// /// /// public static string GetUrlDomainName(string url) { string p = @"^https?://(?[^/]+)(/|$)"; Regex reg = new Regex(p, RegexOptions.IgnoreCase); Match m = reg.Match(url); return m.Groups["domain"].Value.ToString().Trim(); } /// /// 返回URL中结尾的文件名 /// /// /// public static string GetUrlFileName(string url) { if (string.IsNullOrEmpty(url)) return ""; string[] str = url.Split('/'); return str[str.Length - 1].Split('?')[0]; } /// /// 根据字符长度,返回n个*号 /// /// /// 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(); } /// /// 将IP地址转为整数形式 /// /// 整数 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; } /// /// 将整数转为IP地址 /// /// IP地址 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); } /// /// 生成4位数字随机数 /// /// public static string GetRandomInt() { Random random = new Random(); return (random.Next(1000, 9999).ToString()); } /// /// MD5函数 /// 返回32位大写结果. /// /// 原始字符串 /// MD5结果 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(); } /// /// 检测是否符合email格式 /// /// 要判断的email字符串 /// 判断结果 public static bool IsValidEmail(string strEmail) { return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]"); } /// /// 是否为ip /// /// /// 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?)$"); } /// /// 获得当前页面客户端的IP /// /// 当前页面客户端的IP 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; } /// /// 写cookie值 /// /// 名称 /// 值 /// 过期时间(分钟) 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); } /// /// 写Cookie值 /// /// 名称 /// 键 /// 值 /// 过期时间 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); } /// /// 读cookie值 /// /// 名称 /// cookie值 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 ""; } /// /// 读cookie值 /// /// 名称 /// cookie值 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 ""; } /// /// 另外一个清理所有Cookie的方法 /// 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(); } } /// /// 移除Cookies /// /// 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(); } } /// /// 将全角数字转换为数字 /// /// /// 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); } /// /// 移除转义字符 如  /// /// /// public static string RemoveEscapeCharacter(string content) { if (string.IsNullOrEmpty(content)) return ""; return Regex.Replace(content, @"&[a-zA-Z]+?;", "", RegexOptions.IgnoreCase); } /// /// 移除Html标记 /// /// /// public static string RemoveHtml(string content) { if (string.IsNullOrEmpty(content)) return ""; return Regex.Replace(content, @"<[^>]*>", "", RegexOptions.IgnoreCase); } /// /// 移除空白 换行 TAB 中文空白 /// /// /// public static string RemoveSpacing(string content) { if (string.IsNullOrEmpty(content)) return ""; return Regex.Replace(content, @"\s", "", RegexOptions.IgnoreCase); } /// /// 检测是否有Sql危险字符 /// /// 要判断字符串 /// 判断结果 public static bool IsSafeSqlString(string str) { return Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); } /// /// 检测字符号是否只包括数字、字母和中文 /// /// 要判断字符串 /// 判断结果 public static bool IsSafeUserInfoString(string str) { return Regex.IsMatch(str, "[\\s\\p{P}\n\r=<>$>+¥^]"); } /// /// 判断是否为base64字符串 /// /// /// public static bool IsBase64String(string str) { //A-Z, a-z, 0-9, +, /, = return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]"); } /// /// 判断对象是否为Int32类型的数字 /// /// /// public static bool IsNumeric(object Expression) { return Validator.IsNumeric(Expression); } /// /// 从HTML中获取文本,保留br,p,img /// /// /// public static string GetTextFromHTML(string HTML) { System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); return regEx.Replace(HTML, ""); } /// /// 从HTML中获取文本,保留tr,td,strong,br,span,p /// /// /// 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); } /// /// object型转换为bool型 /// /// 要转换的字符串 /// 缺省值 /// 转换后的bool类型结果 public static bool ObjectToBool(object expression, bool defValue) { return TypeConverter.ObjectToBool(expression, defValue); } /// /// string型转换为bool型 /// /// 要转换的字符串 /// 缺省值 /// 转换后的bool类型结果 public static bool StrToBool(string expression, bool defValue) { return TypeConverter.StrToBool(expression, defValue); } /// /// 将对象转换为Int32类型 /// /// 要转换的字符串 /// 缺省值 /// 转换后的int类型结果 public static int StrToInt(object expression, int defValue) { return TypeConverter.ObjectToInt(expression, defValue); } /// /// 将字符串转换为Int32类型 /// /// 要转换的字符串 /// 缺省值 /// 转换后的int类型结果 public static int StrToInt(string expression, int defValue) { return TypeConverter.StrToInt(expression, defValue); } /// /// 将字符串转换为DateTime类型 /// /// 要转换的字符串 /// 缺省值 /// 转换后的DateTime类型结果 public static DateTime StrToDateTime(string expression, DateTime defValue) { return TypeConverter.StrToDateTime(expression, defValue); } /// /// Object型转换为float型 /// /// 要转换的字符串 /// 缺省值 /// 转换后的int类型结果 public static float StrToFloat(object strValue, float defValue) { return TypeConverter.StrToFloat(strValue, defValue); } /// /// string型转换为float型 /// /// 要转换的字符串 /// 缺省值 /// 转换后的int类型结果 public static float StrToFloat(string strValue, float defValue) { return TypeConverter.StrToFloat(strValue, defValue); } /// /// 判断给定的字符串数组(strNumber)中的数据是不是都为数值型 /// /// 要确认的字符串数组 /// 是则返加true 不是则返回 false public static bool IsNumericArray(string[] strNumber) { return Validator.IsNumericArray(strNumber); } /// /// 得到距离开奖的时间差 /// /// 现在时间 /// 开奖时间 /// 过期时间 增加的天数 /// 时间差 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; } /// /// 取页面源码 /// /// /// 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 ""; } } } }