using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Caching; using System.Web.Security; namespace YMQ.MAdmin.Tools { /*** * 文 件 名:Utils * 命名空间:YMQ.MAdmin.Tools * 功 能:一些常用的验证 * 作 者:mxp * 生成日期:2015/12/30 10:54:48 * 版 本 号:V1.0.0.0 * 修改日志: * */ public static class Utils { /// <summary> /// 判断用户名的长度是否符合要求 /// </summary> /// <param name="str">要判断的用户名</param> /// <param name="minLength">最小长度</param> /// <param name="maxLength">最大长度</param> /// <returns></returns> public static bool IsUserName(string str,int minLength,int maxLength) { if (str == null) return false; if (StrLength(str) <=minLength || StrLength(str) >=maxLength) return false; return (Regex.IsMatch(str, @"^([a-zA-Z0-9]|[_@]){5,16}$")); } /// <summary> /// 判断姓名(中文或英文) /// </summary> /// <param name="str">名字</param> /// <returns></returns> public static bool IsRealName(string str) { if (str == null) return false; str = str.Trim(); return (Regex.IsMatch(str, @"^[(\u4e00-\u9fa5)|(a-zA-Z )]{2,20}$")); } /// <summary> /// 判断密码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsPassword(string str) { if (str == null) return false; return (Regex.IsMatch(str, @"^[a-zA-Z0-9\-_\.\!\@\#\$\^\*]{6,20}$")); } /// <summary> /// 判断Email /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsEmail(string str) { if (str == null) return false; return (Regex.IsMatch(str, @"[_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+$")); } /// <summary> /// 获取字符串长度 /// </summary> /// <param name="str"></param> /// <returns></returns> public static int StrLength(string str) { byte[] strArray = Encoding.Default.GetBytes(str); return strArray.Length; } /// <summary> /// 判断手机号码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsMobilePhone(string str) { if (str == null) return false; return (Regex.IsMatch(str, @"^((1)(3|5|8)[0-9]{9})$")); } /// <summary> /// 判断是否为整数 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsInt(string str) { if (str == null) return false; return (Regex.IsMatch(str, @"^[1-9]{1}[0-9]{0,6}$")); } /// <summary> /// 判断日期 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsDate(string str) { if (str == null) return false; try { Convert.ToDateTime(str); return true; } catch { return false; } } /// <summary> /// MD5加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string MD5(string str) { if (str == null) return ""; return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5").ToUpper(); } /// <summary> /// 判断是否为IP地址 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsIPAddress(string str) { if (str == null || str == string.Empty || str.Length < 7 || str.Length > 15) return false; string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$"; Regex regex = new Regex(regformat, RegexOptions.IgnoreCase); return regex.IsMatch(str); } /// <summary> /// 判断是否为汉字 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsChinese(string str) { if (str == null) return false; return (Regex.IsMatch(str, @"^[\u4E00-\u9FA5\uf900-\ufa2d]")); } /// <summary> /// 判断是否为数字 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsNumber(string str) { if (string.IsNullOrEmpty(str)) return false; return Regex.IsMatch(str, @"^[0-9]"); } /// <summary> /// 判断是否为英文字母 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsEnglish(string str) { if (string.IsNullOrEmpty(str)) return false; return Regex.IsMatch(str, @"^[a-zA-Z]"); } /// <summary> /// 获取客户端真实IP,如果有代理则取第一个非内网地址 /// </summary> public static string IPAddress { get { string result = String.Empty; result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (result != null && result != String.Empty) { if (result.IndexOf(".") == -1) result = null; else { if (result.IndexOf(",") != -1) { result = result.Replace(" ", "").Replace("'", ""); string[] temparyip = result.Split(",;".ToCharArray()); for (int i = 0; i < temparyip.Length; i++) { if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.") { return temparyip[i]; } } } else if (IsIPAddress(result)) return result; else result = null; } } result = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; if (null == result || result == String.Empty) result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; if (result == null || result == String.Empty) result = HttpContext.Current.Request.UserHostAddress; if (result == "::1") result = "127.0.0.1"; return result; } } /// <summary> /// 判断是否存在ArrayList中 /// </summary> /// <param name="List"></param> /// <param name="val"></param> /// <returns></returns> public static bool InArrayList(ArrayList List, string val) { if (string.IsNullOrEmpty(val)) return false; return List.Contains(val); } /// <summary> /// 查询编码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsTradeCode(string str) { if (str == null) return false; return (Regex.IsMatch(str, @"^[a-zA-Z]{3}[\d]{10}$")); } /// <summary> /// 格式化金额 /// </summary> /// <param name="str"></param> /// <returns>返回 ###,###,###</returns> public static string FormatMoney(string str) { if (!IsInt(str)) return ""; return Convert.ToInt32(str).ToString("###,###,###"); } /// <summary> /// 人民币大写 /// </summary> /// <param name="num"></param> /// <returns></returns> public static string FormatMoneyCN(string num) { if (num == null) return ""; if (num == "0") return "零元整"; num = num.Trim().Replace(",", ""); string[] part = num.Split('.'); string newchar = "", tmpnewchar; char perchar; string[] BB = "零,壹,贰,叁,肆,伍,陆,柒,捌,玖".Split(','); for (int i = part[0].Length - 1; i >= 0; i--) { perchar = part[0][i]; tmpnewchar = BB[Convert.ToInt32(part[0].Substring(i, 1))]; switch (part[0].Length - i - 1) { case 0: tmpnewchar += "元"; break; case 1: if (perchar != '0') tmpnewchar += "拾"; break; case 2: if (perchar != '0') tmpnewchar += "佰"; break; case 3: if (perchar != '0') tmpnewchar += "仟"; break; case 4: tmpnewchar += "万"; break; case 5: if (perchar != '0') tmpnewchar += "拾"; break; case 6: if (perchar != '0') tmpnewchar += "佰"; break; case 7: if (perchar != '0') tmpnewchar += "仟"; break; case 8: tmpnewchar += "亿"; break; case 9: tmpnewchar += "拾"; break; } newchar = tmpnewchar + newchar; } //小数点之后进行转化 if (num.IndexOf(".") != -1) { //小数点之后只能保留两位,系统将自动截段 if (part[1].Length > 2) { part[1] = part[1].Substring(0, 2); } for (int i = 0; i < part[1].Length; i++) { tmpnewchar = BB[Convert.ToInt32(part[1].Substring(i, 1))]; if (i == 0) tmpnewchar += "角"; if (i == 1) tmpnewchar += "分"; newchar += tmpnewchar; } } //替换所有无用汉字 while (newchar.IndexOf("零零") != -1) newchar = newchar.Replace("零零", "零"); newchar = newchar.Replace("零亿", "亿"); newchar = newchar.Replace("亿万", "亿"); newchar = newchar.Replace("零万", "万"); newchar = newchar.Replace("零元", "元"); newchar = newchar.Replace("零角", ""); newchar = newchar.Replace("零分", ""); if (newchar.EndsWith("元") || newchar.EndsWith("角")) newchar += "整"; return newchar; } /// <summary> /// 输出js的alert,并返回上一页 /// </summary> /// <param name="str"></param> public static void Msg(string str) { HttpContext.Current.Response.Write("<script>alert('" + str + "');self.history.back();</script>"); HttpContext.Current.Response.End(); } /// <summary> /// 输出js的alert,并返回指定url的页面 /// </summary> /// <param name="str"></param> /// <param name="url"></param> public static void Msg2(string str, string url) { HttpContext.Current.Response.Write("<script>alert('" + str + "');self.location.replace('" + url + "');</script>"); HttpContext.Current.Response.End(); } /// <summary> /// URL 编码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Escape(string str) { if (str == null) return String.Empty; StringBuilder sb = new StringBuilder(); int len = str.Length; for (int i = 0; i < len; i++) { char c = str[i]; if (Char.IsLetterOrDigit(c) || c == '-' || c == '_' || c == '/' || c == '\\' || c == '.') sb.Append(c); else sb.Append(Uri.HexEscape(c)); } return sb.ToString(); } /// <summary> /// URL 解码 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string UnEscape(string str) { if (str == null) return String.Empty; StringBuilder sb = new StringBuilder(); int len = str.Length; int i = 0; while (i != len) { if (Uri.IsHexEncoding(str, i)) sb.Append(Uri.HexUnescape(str, ref i)); else sb.Append(str[i++]); } return sb.ToString(); } #region 区分中英文的字符串截取 /// <summary> /// 区分中英文的字符串截取,中文两个字符长度 /// </summary> /// <param name="inputString">要截取的字符串</param> /// <param name="count">要截取的长度</param> /// <returns></returns> public static string GetChineseSubString(string inputString, int count) { return GetChineseSubString(inputString, count, ".."); } private static string GetChineseSubString(string inputString, int count, string addition) { int limit = count * 2; if (limit >= GetChineseStringLength(inputString)) { return inputString; } else { limit -= addition.Length; StringBuilder sb = new StringBuilder(); char[] chars = inputString.ToCharArray(); for (int i = 0; i < chars.Length; i++) { char c = chars[i]; sb.Append(c); if (c > 127) { limit -= 2; if (limit < 0) { sb.Length--; break; } } else { limit--; } if (limit == 0) { break; } } return sb.ToString() + addition; } } private static int GetChineseStringLength(string inputString) { int length = 0; if (!string.IsNullOrEmpty(inputString)) { char[] chars = inputString.ToCharArray(); for (int i = 0; i < chars.Length; i++) { if (chars[i] > 127) { length += 2; } else { length++; } } } return length; } #endregion /// <summary> /// 获取当前用户的名称 /// </summary> /// <returns></returns> public static string getCookieUser_Cd() { if (HttpContext.Current.User.Identity.IsAuthenticated) { return HttpContext.Current.User.Identity.Name; } else { return ""; } } /// <summary> ///过滤特殊字符串 ///</summary> public static string htmlInput(string str) { if (str == null || str == "") return ""; str = str.Replace(";", ""); str = str.Replace("'", ""); str = str.Replace("&", ""); str = str.Replace("%20", ""); str = str.Replace("--", ""); str = str.Replace("==", ""); str = str.Replace("<", ""); str = str.Replace(">", ""); str = str.Replace("%", ""); return str; } /// <summary> /// 获取web.config里配置项 /// </summary> /// <param name="configName">key</param> /// <returns></returns> public static string GetConfig(string configName) { string val = HttpRuntime.Cache[configName] != null ? HttpRuntime.Cache[configName].ToString() : ""; if (string.IsNullOrEmpty(val)) { //将配置项缓存起来,当Web.config发生变更能自动清除现在缓存项 val = System.Configuration.ConfigurationManager.AppSettings[configName]; string filePath = HttpContext.Current.Server.MapPath("web.config"); CacheDependency dependency = new CacheDependency(filePath); if (!string.IsNullOrEmpty(val)) { HttpRuntime.Cache.Add(configName, val, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.High, null); } } return val; } /// <summary> /// 去掉中间多个空格,只需保留一个空格 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string DelMinTrim(string str) { str = str.Replace(" ", " ").Trim(); while (str.IndexOf(" ") > 0) str = str.Replace(" ", " "); return str; } /// <summary> /// 将对象的所有属性生成字符串 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetObjectContent(object obj) { if (obj == null) return string.Empty; StringBuilder str = new StringBuilder(); //获得对象的类型 Type t = obj.GetType(); //遍历类型的属性,获得属性信息 foreach (PropertyInfo pi in t.GetProperties()) { try { //根据属性信息获得该实例对应的属性值。 object v = pi.GetValue(obj, null); if (v != null) { str.AppendFormat("【{0}】={1},", pi.Name, v); } } catch { } } return str.ToString().TrimEnd(','); } /// <summary> /// 获取参数和值以键值对形式存放在字符串 kxp /// </summary> /// <param name="pars">参数数组</param> /// <returns></returns> public static string GetSqlParameters(params System.Data.SqlClient.SqlParameter[] pars) { string result = string.Empty; foreach (System.Data.SqlClient.SqlParameter item in pars) { result += string.Format("{0}={1},", item.ParameterName, item.Value); } result += string.IsNullOrEmpty(result) ? null : result.TrimEnd(','); return result; } /// <summary> /// 将对象的所有属性生成字符串 /// </summary> /// <param name="objOld">修改之前数据对象</param> /// <param name="objNew">修改之后数据对象</param> /// <param name="pkName">主键字段名称,或者能确定数据身份且不能修改的关键列名</param> /// <returns></returns> public static string GetObjectContent<T>(T objOld, T objNew, string pkName) { if (objOld == null || objNew == null) return string.Empty; StringBuilder str = new StringBuilder(); //获得对象的类型 Type t = objOld.GetType(); string head = string.Empty; //遍历类型的属性,获得属性信息 foreach (PropertyInfo pi in t.GetProperties()) { try { //根据属性信息获得该实例对应的属性值。 object v1 = pi.GetValue(objOld, null); object v2 = pi.GetValue(objNew, null); if (v1 == null) v1 = "null"; if (v2 == null) v2 = "null"; if (!string.IsNullOrEmpty(pkName) && pi.Name.ToUpper() == pkName.ToUpper()) head = string.Format("【{0}】={1}:", pkName, v1); if (v1.ToString() != v2.ToString()) str.AppendFormat("【{0}】由{1}变更为{2},", pi.Name, v1, v2); } catch { } } return head + str.ToString().TrimEnd(','); } /// <summary> /// 将DataTable数据生成字符串 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string GetTableContent(DataTable dt) { StringBuilder str = new StringBuilder(); if (dt == null || dt.Rows.Count == 0) return string.Empty; foreach (DataRow dr in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i++) { str.AppendFormat("【{0}】={1},", dt.Columns[i], dr[dt.Columns[i]]); } str.Remove(str.Length - 1, 1); str.Append(string.Empty); } return str.ToString(); } #region 全角半角转换 /// <summary> /// 转全角的函数(SBC case) /// </summary> /// <param name="input">任意字符串</param> /// <returns>全角字符串</returns> ///<remarks> ///全角空格为12288,半角空格为32 ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 ///</remarks> 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); } /// <summary> 转半角的函数(DBC case) </summary> /// <param name="input">任意字符串</param> /// <returns>半角字符串</returns> ///<remarks> ///全角空格为12288,半角空格为32 ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248 ///</remarks> 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); } #endregion /// <summary> /// 随机生成数字加字母组合码 /// </summary> /// <param name="Length"></param> /// <returns></returns> public static string GenerateRandom(int Length) { Random rd = new Random(); return (rd.Next(100000, 999999)).ToString(); //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' //}; //StringBuilder newRandom = new StringBuilder(62); //Random rd = new Random(); //for (int i = 0; i < Length; i++) //{ // newRandom.Append(constant[rd.Next(62)]); //} //return newRandom.ToString(); } /// <summary> /// 保留两位小数 格式化0.00 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string FormatString(double str) { string obj = str.ToString("0.00"); if (obj == "0") { return obj; } var o = obj.Split('.'); if (o.Length > 0) { if (o[1] == "00") { return o[0]; } else { return Convert.ToDecimal(obj).ToString("0.00"); } } else { return obj; } } /// <summary> /// 获取时间差 /// </summary> /// <param name="dtEnd">时间一(比较靠后的时间)</param> /// <param name="dtNow">时间二</param> /// <returns>返回格式00天00小时00分00秒</returns> public static string GetRemain(DateTime dtEnd, DateTime dtNow) { if (dtEnd < dtNow) { return "已结束"; } string alltime = string.Empty; TimeSpan ts = dtEnd - dtNow; //时间差 string timestr = (ts.Days.ToString("").PadLeft(2, '0') + "天" + ts.Hours.ToString("").PadLeft(2, '0') + "时" + ts.Minutes.ToString("").PadLeft(2, '0') + "分" + ts.Seconds.ToString("").PadLeft(2, '0') + "秒"); alltime = timestr; return alltime; } /// <summary> /// 获取时间差(返回 秒) /// </summary> /// 创 建 人:renhz /// 创建日期:2012-10-14 /// <param name="dtEnd">时间一(比较靠后的时间)</param> /// <param name="dtNow">时间二</param> /// <returns>返回格N秒</returns> public static string GetRemain_s(DateTime dtEnd, DateTime dtNow) { if (dtEnd < dtNow) { return "竞拍结束"; } string alltime = string.Empty; TimeSpan ts = dtEnd - dtNow; //时间差 string timestr = (ts.TotalSeconds.ToString()); alltime = timestr; return alltime; } /// <summary> /// 将对象转换成sql参数 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static SqlParameter[] getParsByObj(object obj) { Type type = obj.GetType(); PropertyInfo[] pInfo = type.GetProperties(); int iln = pInfo.Length; SqlParameter[] sqlPars = new SqlParameter[iln]; for (int i = 0; i < iln; i++) { sqlPars[i] = new SqlParameter(); sqlPars[i].ParameterName = "@" + pInfo[i].Name; sqlPars[i].Value = pInfo[i].GetValue(obj, null); } return sqlPars; } /// <summary> /// 格式化显示位数 /// </summary> /// <param name="str">需要格式的字符串</param> /// <param name="length">位数</param> /// <returns></returns> public static string FormatDateDiff(string str, int length) { if (str.Trim().Length == length) { return str; } string rstr = string.Empty; for (int i = 0; i < length - str.Trim().Length; i++) { rstr += "0"; } return rstr + str; } /// <summary> /// 获取次实例的主机部分 /// </summary> /// <returns></returns> public static string domain() { return HttpContext.Current.Request.Url.Host; } /// <summary> /// 检测报告路径 /// </summary> public static string ReportPath { get { return ConfigurationManager.AppSettings["reportPath"]; } } /// <summary> /// 读取检测报告类型 /// </summary> public static string ReportType { get { int optDataType = 85; string reportType = string.Empty; switch (optDataType) { case 85: reportType = "unicom"; break; } return reportType; } } /// <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*$|^c:\\con\\con$|[%,\*" + "\"" + @"\s\t\<\>\&]|游客|^Guest"); } /// <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> /// 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); } } }
C#中一些常用的方法,工作中用到的,记录下来方便以后使用