using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Security.Cryptography; using System.Reflection; using System.Configuration; using System.Net; using System.IO; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; namespace COMCMS.Common { /// /// 常用函数帮助类 /// public class Utils { public static IConfiguration Configuration { get; set; } static Utils() { ////ReloadOnChange = true 当appsettings.json被修改时重新加载 //Configuration = new ConfigurationBuilder() //.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true }) //.Build(); } public static void AddUtils(IConfiguration configuration) { Configuration = configuration; } #region 静态变量 /// /// 得到正则编译参数设置 /// /// 参数设置 public static RegexOptions GetRegexCompiledOptions() { return RegexOptions.None; } public static string PrefixKey { get { string strPrefixKey = Configuration["SystemSetting:COMCMSPrefixKey"];// ConfigurationManager.AppSettings["COMCMSPrefixKey"]; if (string.IsNullOrEmpty(strPrefixKey)) { strPrefixKey = "comcmsntc_"; } return strPrefixKey; } } /// /// 与小程序验签的盐值 /// public static readonly string SIGNSALT = "comcms";// ConfigurationManager.AppSettings["SignSalt"]; /// /// 订单状态 "未确认", "已确认", "已完成", "已取消" /// public static string[] OrdersState = { "未确认", "已确认", "已完成", "已取消" }; /// /// 支付状态 { "未支付", "已支付", "已退款" } /// public static string[] PaymentState = { "未支付", "已支付", "已退款" }; /// /// 配送状态 "未配送", "配货中", "已配送", "已收到", "退货中", "已退货" /// public static string[] DeliverState = { "未配送", "配货中", "已配送", "已收到", "退货中", "已退货" }; /// /// cms类型 /// public enum CMSType { /// /// 文章分类 /// ArticleCategory=0, /// /// 文章 /// Article=1, /// /// 商品分类 /// ProductCategory=2, /// /// 商品详情 /// Product=3, /// /// 首页 /// Home=99 } #endregion #region 验证部分 /// /// 验证是否为正整数 /// /// /// public static bool IsInt(string str) { if (string.IsNullOrWhiteSpace(str)) return false; //return Regex.IsMatch(str, @"^[0-9]*$"); return Regex.IsMatch(str, @"^(-?)(\d+)$"); } /// /// 验证是否为字母或者数字 /// /// /// public static bool IsWords(string str) { return Regex.IsMatch(str, @"^[A-Za-z0-9]+$"); } /// /// 判断是否为正确的 /// /// /// public static bool IsFilePath(string str) { //A-Z, a-z, 0-9, -, /, = return Regex.IsMatch(str, @"[A-Za-z0-9-\/]"); } /// /// 验证对象是否为货币格式 /// /// 验证对象 /// 货币格式返回true,否则返回false public static bool IsDecimal(object obj) { bool flag = true; if (obj.GetType() != decimal.Parse("10.11").GetType()) { try { decimal.Parse((string)obj); } catch { flag = false; } } return flag; } /// /// 检测是否是正确的Url /// /// 要验证的Url /// 判断结果 public static bool IsURL(string strUrl) { return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$"); } /// /// 获取当前网站根目录网址 不带 / /// /// public static string GetServerUrl() { string http = "http://"; if (MyHttpContext.Current.Request.IsHttps) //判断是否是https { http = "https://"; } string port = MyHttpContext.Current.Request.Host.Port.ToString(); if (string.IsNullOrEmpty(port) || port == "80" || port == "443") return http + MyHttpContext.Current.Request.Host.Host; else return http + MyHttpContext.Current.Request.Host.Host + ":" + port; } /// /// 判断是否为base64字符串 /// /// /// public static bool IsBase64String(string str) { //A-Z, a-z, 0-9, +, /, = return Regex.IsMatch(str, @"[A-Za-z0-9\+\/\=]"); } /// /// 检测是否有Sql危险字符 /// /// 要判断字符串 /// 判断结果 public static bool IsSafeSqlString(string str) { return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); } /// /// 验证是否为手机号码 /// /// 手机号码 /// public static bool IsTel(string str) { if (str.Length != 11) return false; return Regex.IsMatch(str, @"^1[3|4|5|7|8|9][0-9]\d{4,8}$"); } /// /// 是否为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?)$"); } /// /// 检测是否符合email格式 /// /// 要判断的email字符串 /// 判断结果 public static bool IsValidEmail(string strEmail) { return Regex.IsMatch(strEmail, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]"); } public static bool IsIPSect(string ip) { return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){2}((2[0-4]\d|25[0-5]|[01]?\d\d?|\*)\.)(2[0-4]\d|25[0-5]|[01]?\d\d?|\*)$"); } /// /// 返回指定IP是否在指定的IP数组所限定的范围内, IP数组内的IP地址可以使用*表示该IP段任意, 例如192.168.1.* /// /// /// /// public static bool InIPArray(string ip, string[] iparray) { string[] userip = Utils.SplitString(ip, @"."); for (int ipIndex = 0; ipIndex < iparray.Length; ipIndex++) { string[] tmpip = Utils.SplitString(iparray[ipIndex], @"."); int r = 0; for (int i = 0; i < tmpip.Length; i++) { if (tmpip[i] == "*") return true; if (userip.Length > i) { if (tmpip[i] == userip[i]) r++; else break; } else break; } if (r == 4) return true; } return false; } /// /// 分割字符串 /// public static string[] SplitString(string strContent, string strSplit) { if (!string.IsNullOrWhiteSpace(strContent)) { if (strContent.IndexOf(strSplit) < 0) return new string[] { strContent }; return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase); } else return new string[0] { }; } /// /// 判断元素是否在列表中 /// /// 判断字符 /// 使用,号隔开 /// public static bool IsInArrayString(string strin, string arraystring) { bool flag = false; if (!string.IsNullOrEmpty(arraystring)) { string[] srrids = arraystring.Split(new string[] { "," }, StringSplitOptions.None); List kids = new List(); foreach (string s in srrids) { if (!string.IsNullOrEmpty(s)) { kids.Add(s.Trim());//加入允许使用的商品列表 } } if (kids.FindIndex(s => s == strin) >= 0) flag = true; } return flag; } /// /// 验证身份证号码 /// /// /// public static bool CheckCardId(string str) { if (string.IsNullOrWhiteSpace(str) || str.Length != 18) return false; string number17 = str.Substring(0, 17); string number18 = str.Substring(17); string check = "10X98765432"; int[] num = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; int sum = 0; for (int i = 0; i < number17.Length; i++) { sum += Convert.ToInt32(number17[i].ToString()) * num[i]; } sum %= 11; if (number18.Equals(check[sum].ToString(), StringComparison.OrdinalIgnoreCase)) { return true; } else { return false; } } #endregion #region 获取部分 /// /// 获取配置 /// /// 路径,如:SystemSetting:COMCMSPrefixKey /// public static string GetSetting(string path) { string value = Configuration[path]; return value; } /// /// 返回字符串真实长度, 1个汉字长度为2 /// /// 字符长度 public static int GetStringLength(string str) { return Encoding.UTF8.GetBytes(str).Length; } /// /// MD5函数 /// /// 原始字符串 /// MD5结果 public static string MD5(string str) { using (var md5 = System.Security.Cryptography.MD5.Create()) { var result = md5.ComputeHash(Encoding.UTF8.GetBytes(str)); var strResult = BitConverter.ToString(result); return strResult.Replace("-", ""); } } /// /// SHA256函数 /// /// /// 原始字符串 /// SHA256结果 public static string SHA256(string str) { using(var sha256 = System.Security.Cryptography.SHA256.Create()) { var result = sha256.ComputeHash(Encoding.UTF8.GetBytes(str)); var strResult = BitConverter.ToString(result); return strResult.Replace("-", ""); } } /// /// 获取指定文件的扩展名 /// /// 指定文件名 /// 扩展名(.xxx) public static string GetFileExtName(string fileName) { if (string.IsNullOrWhiteSpace(fileName) || fileName.IndexOf('.') <= 0) return ""; fileName = fileName.ToLower().Trim(); return fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.')); } private static Random rd = new Random(); /// /// 获取随机整数 /// /// 最小值 /// 最大值 /// public static int GetRND(int min, int max) { Random rnd = new Random(Guid.NewGuid().GetHashCode()); return rnd.Next(min, max); } /// /// 生成上传文件保存名字 /// /// 不带扩展名名字 public static string CreateUploadSaveName() { string saveName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + GetRND(1000, 9999).ToString(); return saveName; } /// /// 生成订单号 /// /// 订单号 public static string GetOrderNum() { string ordernum = DateTime.Now.ToString("yyyyMMddHHmm") + GetRND(1000, 9999).ToString(); return ordernum; } private static char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; /// /// 获取随机字符串 /// /// 字符长度 /// 返回随机字符串 public static string GetRandomChar(int strLength) { StringBuilder newRandom = new StringBuilder(62); Random rd = new Random(Guid.NewGuid().GetHashCode()); for (int i = 0; i < strLength; i++) { newRandom.Append(constant[rd.Next(62)]); } return newRandom.ToString(); } /// /// 获取当前附近坐标点 /// /// 经度 /// 纬度 /// 附近半径,千米,默认0.5=500米 /// 一维数组:0:最小经度,1:最大经度;2:最小纬度;3:最大纬度 public static double[] FindNeighPosition(double longitude, double latitude, double aboutRadius = 0.5) { double[] result = new double[4]; //先计算查询点的经纬度范围 double r = 6371;//地球半径千米 double dis = aboutRadius;//0.5千米距离 double dlng = 2 * Math.Asin(Math.Sin(dis / (2 * r)) / Math.Cos(latitude * Math.PI / 180)); dlng = dlng * 180 / Math.PI;//角度转为弧度 double dlat = dis / r; dlat = dlat * 180 / Math.PI; double minlat = latitude - dlat; double maxlat = latitude + dlat; double minlng = longitude - dlng; double maxlng = longitude + dlng; result[0] = minlng; result[1] = maxlng; result[2] = minlat; result[3] = maxlat; return result; } /// /// 获取文件名字,不带扩展名 /// /// /// public static string GetFileNameWithoutExtension(string fileName) { int length = fileName.Length - 1, dotPos = fileName.IndexOf("."); if (dotPos == -1) return fileName; return fileName.Substring(0, dotPos); } /// /// 创建一个短的GUID /// /// 字符串类型 public static string GetShortGUId() { long i = 1; foreach (byte b in Guid.NewGuid().ToByteArray()) { i *= ((int)b + 1); } return string.Format("{0:x}", i - DateTime.Now.Ticks); } /// /// 判断文件名是否为浏览器可以直接显示的图片文件名 /// /// 文件名 /// 是否可以直接显示 public static bool IsImgFilename(string filename) { filename = filename.Trim(); if (filename.EndsWith(".") || filename.IndexOf(".") == -1) return false; string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower(); return (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif"); } /// /// 获取HTML里面首张图片 /// /// html内容 /// 首张图片地址,为空则图片不存在 public static string GetHTML1stImgSrc(string html) { string imgsrc = ""; Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase); MatchCollection m = reg.Matches(html); if (m.Count > 0) { for (int i = 0; i < m.Count; i++) { if (!string.IsNullOrEmpty(m[i].Groups[1].Value) && IsImgFilename(m[i].Groups[1].Value.ToString())) { imgsrc = m[i].Groups[1].Value.ToString(); break; } } } else { imgsrc = ""; } return imgsrc; } /// /// 获取所有图片 /// /// 图片字符串 /// 图片地址 public static List GetAllPic(string pic) { if (!string.IsNullOrEmpty(pic)) { List list = new List(); string[] arrpic = pic.Split(new string[] { "|||" }, StringSplitOptions.None); foreach (string picurl in arrpic) list.Add(picurl); return list; } else { return null; } } /// /// 从字符串的指定位置截取指定长度的子字符串 /// /// 原字符串 /// 子字符串的起始位置 /// 子字符串的长度 /// 子字符串 public static string CutString(string str, int startIndex, int length) { if (startIndex >= 0) { if (length < 0) { length = length * -1; if (startIndex - length < 0) { length = startIndex; startIndex = 0; } else startIndex = startIndex - length; } if (startIndex > str.Length) return ""; } else { if (length < 0) return ""; else { if (length + startIndex > 0) { length = length + startIndex; startIndex = 0; } else return ""; } } if (str.Length - startIndex < length) length = str.Length - startIndex; return str.Substring(startIndex, length); } /// /// 截取字符串 /// /// 字符串 /// 截取长度 /// public static string CutString(string strInput, int intLen) { if (string.IsNullOrEmpty(strInput)) return ""; strInput = strInput.Trim(); byte[] myByte = Encoding.UTF8.GetBytes(strInput); //Response.Write("cutString Function is::" + myByte.Length.ToString()); if (myByte.Length > intLen + 2) { //截取操作 string resultStr = ""; for (int i = 0; i < strInput.Length; i++) { byte[] tempByte = Encoding.UTF8.GetBytes(resultStr); if (tempByte.Length < intLen) { resultStr += strInput.Substring(i, 1); } else { break; } } return resultStr + "..."; } else { return strInput; } } /// /// 判断是否是GUID /// /// /// public static bool IsGuidByParse(string strSrc) { Guid g = Guid.Empty; return Guid.TryParse(strSrc, out g); } /// /// 获取广告类型 /// /// /// public static string GetAdsType(int tid) { string tname = "代码广告"; switch (tid) { case 0: break; case 1: tname = "文字广告"; break; case 2: tname = "图片广告"; break; case 3: tname = "Flash广告"; break; case 4: tname = "幻灯片广告"; break; case 5: tname = "漂浮广告"; break; case 6: tname = "对联广告"; break; } return tname; } /// /// 获取缩略图地址 /// /// /// public static string GetThumbImg(string imgsrc) { if (!string.IsNullOrEmpty(imgsrc)) { return imgsrc.Replace("/userfiles/", "/userfiles/_thumbs/"); } else return ""; } /// /// 获取用户IP地址 /// /// 用户IP地址 public static string GetIP() { string userHostAddress = MyHttpContext.Current.Request.HttpContext.Connection.RemoteIpAddress.ToString(); //2019-05-11 增加反向代理获取真实IP string xForwardedForAddress = MyHttpContext.Current.Request.Headers["X-Forwarded-For"]; if (!string.IsNullOrEmpty(userHostAddress) && !string.IsNullOrEmpty(xForwardedForAddress) && userHostAddress != xForwardedForAddress) { return xForwardedForAddress; } if (!string.IsNullOrEmpty(userHostAddress) && Utils.IsIP(userHostAddress)) { if (userHostAddress == "::1") userHostAddress = "127.0.0.1"; return userHostAddress; } return "127.0.0.1"; } /// /// 时间戳转换成DateTime格式 /// /// /// public static DateTime StampToDateTime(string timeStamp) { //TimeZoneInfo.ConvertTimeFromUtc() DateTime dateTimeStart = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local); long lTime = long.Parse(timeStamp + "0000"); TimeSpan toNow = new TimeSpan(lTime); return dateTimeStart.Add(toNow); } /// /// 获取时间戳 /// /// public static string GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } /// /// 获取JS时间戳 /// /// public static string GetJSTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds).ToString(); } /// /// 获取当前URL绝对地址 /// /// public static string GetNowURL() { string url = GetServerUrl() + MyHttpContext.Current.Request.Path; string querystring = MyHttpContext.Current.Request.QueryString.ToString(); if (!string.IsNullOrWhiteSpace(querystring)) url = url + querystring; return url; } /// /// 获取post表单金钱字段值 /// /// /// public static decimal GetPostFormMoney(string inputName) { string v = MyHttpContext.Current.Request.Form[inputName]; decimal price = 0M; if (!IsDecimal(v) && decimal.Parse(v) < 0) v = "0"; price = decimal.Parse(v); return price; } /// /// 获取get表单金钱字段值 /// /// /// public static decimal GetQueryStringMoney(string inputName) { string v = MyHttpContext.Current.Request.Query[inputName]; decimal price = 0M; if (!IsDecimal(v) && decimal.Parse(v) < 0) v = "0"; price = decimal.Parse(v); return price; } #endregion #region 处理部分 //常用处理函数 /// /// 格式化处理SQL字符串 /// /// 替换单引号后的字符串 /// 格式化后的SQL字符串 public static string SqlStr(string str) { string re = ""; try { re = str.Replace("'", "''"); } catch { re = ""; } return re; } /// ///一个处理危险HTML标签的方法 /// /// 要处理的字符串 /// public static string NoHTML(string M_Htmlstring) //去除HTML标记 { if (string.IsNullOrWhiteSpace(M_Htmlstring)) return ""; //删除脚本 M_Htmlstring = Regex.Replace(M_Htmlstring, @"]*?>.*? ", string.Empty, RegexOptions.IgnoreCase); //删除HTML M_Htmlstring = Regex.Replace(M_Htmlstring, @"<(.?[^>]*)>", string.Empty, RegexOptions.IgnoreCase); M_Htmlstring = Regex.Replace(M_Htmlstring, @"([\r\n])[\s]+", string.Empty, RegexOptions.IgnoreCase);//空格换行 M_Htmlstring = Regex.Replace(M_Htmlstring, @"-->", string.Empty, RegexOptions.IgnoreCase);//注释 M_Htmlstring = Regex.Replace(M_Htmlstring, @"