using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Net; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; namespace Mini.Common { public static class Utility { /// /// 获取配置文件中的设置 /// /// /// public static string GetSettingByKey(string key) { return ConfigHelper.GetSectionValue(key); } /// /// DataTable 转list /// /// /// /// public static List ToList(this DataTable dt) where TResult : class, new() { //创建一个属性的列表 List prlist = new List(); //获取TResult的类型实例 反射的入口 Type t = typeof(TResult); //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 Array.ForEach(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); }); //创建返回的集合 List oblist = new List(); foreach (DataRow row in dt.Rows) { //创建TResult的实例 TResult ob = new TResult(); //找到对应的数据,并赋值 prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); }); //放入到返回的集合中. oblist.Add(ob); } return oblist; } /// /// List 转为DataTable /// /// /// /// public static DataTable ToDataTable(List entitys) { //检查实体集合不能为空 if (entitys == null || entitys.Count < 1) { throw new Exception("需转换的集合为空"); } //取出第一个实体的所有Propertie Type entityType = entitys[0].GetType(); PropertyInfo[] entityProperties = entityType.GetProperties(); //生成DataTable的structure //生产代码中,应将生成的DataTable结构Cache起来,此处略 DataTable dt = new DataTable(); for (int i = 0; i < entityProperties.Length; i++) { //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType); dt.Columns.Add(entityProperties[i].Name); } //将所有entity添加到DataTable中 foreach (object entity in entitys) { //检查所有的的实体都为同一类型 if (entity.GetType() != entityType) { throw new Exception("要转换的集合元素类型不一致"); } object[] entityValues = new object[entityProperties.Length]; for (int i = 0; i < entityProperties.Length; i++) { entityValues[i] = entityProperties[i].GetValue(entity, null); } dt.Rows.Add(entityValues); } return dt; } /// /// List 转为DataTable需要指定类型 /// /// /// /// public static DataTable ToOracleDataTable(List entitys) { //检查实体集合不能为空 if (entitys == null || entitys.Count < 1) { throw new Exception("需转换的集合为空"); } //取出第一个实体的所有Propertie Type entityType = entitys[0].GetType(); PropertyInfo[] entityProperties = entityType.GetProperties(); //生成DataTable的structure //生产代码中,应将生成的DataTable结构Cache起来,此处略 DataTable dt = new DataTable(); for (int i = 0; i < entityProperties.Length; i++) { Type colType = entityProperties[i].PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dt.Columns.Add(entityProperties[i].Name, colType); // dt.Columns.Add(entityProperties[i].Name); } //将所有entity添加到DataTable中 foreach (object entity in entitys) { //检查所有的的实体都为同一类型 if (entity.GetType() != entityType) { throw new Exception("要转换的集合元素类型不一致"); } object[] entityValues = new object[entityProperties.Length]; for (int i = 0; i < entityProperties.Length; i++) { entityValues[i] = entityProperties[i].GetValue(entity, null); } dt.Rows.Add(entityValues); } return dt; } /// /// List 转为DataTable需要指定类型 /// /// /// /// public static DataTable ToOracleDataTableToUpper(List entitys) { //检查实体集合不能为空 if (entitys == null || entitys.Count < 1) { throw new Exception("需转换的集合为空"); } //取出第一个实体的所有Propertie Type entityType = entitys[0].GetType(); PropertyInfo[] entityProperties = entityType.GetProperties(); //生成DataTable的structure //生产代码中,应将生成的DataTable结构Cache起来,此处略 DataTable dt = new DataTable(); for (int i = 0; i < entityProperties.Length; i++) { Type colType = entityProperties[i].PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dt.Columns.Add(entityProperties[i].Name.ToUpper(), colType); // dt.Columns.Add(entityProperties[i].Name); } //将所有entity添加到DataTable中 foreach (object entity in entitys) { //检查所有的的实体都为同一类型 if (entity.GetType() != entityType) { throw new Exception("要转换的集合元素类型不一致"); } object[] entityValues = new object[entityProperties.Length]; for (int i = 0; i < entityProperties.Length; i++) { entityValues[i] = entityProperties[i].GetValue(entity, null); } dt.Rows.Add(entityValues); } return dt; } /// /// 把DataTable转成 List集合, 存每一行,集合中放的是键值对字典,存每一列 /// /// 数据表 /// public static List> DataTableToList(DataTable dt) { List> list = new List>(); foreach (DataRow dr in dt.Rows) { Dictionary dic = new Dictionary(); foreach (DataColumn dc in dt.Columns) { dic.Add(dc.ColumnName, dr[dc.ColumnName].ToString()); } list.Add(dic); } return list; } #region 加密 解密 // DES加密偏移量,必须是>=8位长的字符串 private static string iv = "1234567890"; // DES加密的私钥,必须是8位长的字符串DES private static string key = "12345678"; /// /// 对字符串加密后进行编码 /// /// /// public static string EncryptUrlEncode(string sourceString) { sourceString = Encrypt(sourceString); return HttpUtility.UrlEncode(sourceString, Encoding.UTF8); } /// /// 对字符串解码后解密 /// /// /// public static string DecryptUrlDecode(string sourceString) { if (sourceString.IndexOf("%") > -1) sourceString = HttpUtility.UrlDecode(sourceString, Encoding.UTF8); return Decrypt(sourceString); } /// /// 对字符串进行DES加密 /// /// 待加密的字符串 /// 加密后的BASE64编码的字符串 public static string Encrypt(string sourceString) { if (string.IsNullOrEmpty(sourceString)) { return string.Empty; } else { byte[] btKey = Encoding.Default.GetBytes(key); byte[] btIV = Encoding.Default.GetBytes(iv); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); using (MemoryStream ms = new MemoryStream()) { byte[] inData = Encoding.Default.GetBytes(sourceString); try { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write)) { cs.Write(inData, 0, inData.Length); cs.FlushFinalBlock(); } return Convert.ToBase64String(ms.ToArray()); } catch (Exception ex) { throw ex; } } } } /// /// 对DES加密后的字符串进行解密 /// /// 待解密的字符串 /// 解密后的字符串 public static string Decrypt(string encryptedString) { if (string.IsNullOrEmpty(encryptedString)) { return string.Empty; } else { byte[] btKey = Encoding.Default.GetBytes(key); byte[] btIV = Encoding.Default.GetBytes(iv); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); using (MemoryStream ms = new MemoryStream()) { byte[] inData = Convert.FromBase64String(encryptedString); try { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write)) { cs.Write(inData, 0, inData.Length); cs.FlushFinalBlock(); } return Encoding.Default.GetString(ms.ToArray()); } catch (Exception ex) { throw ex; } } } } public static string Left(string sSource, int iLength) { return sSource.Substring(0, iLength > sSource.Length ? sSource.Length : iLength); } public static string Right(string sSource, int iLength) { return sSource.Substring(iLength > sSource.Length ? 0 : sSource.Length - iLength); } /// /// md5加密 /// /// /// public static string EncryptMD5(string input) { string output = null; if (string.IsNullOrEmpty(input)) { output = input; } else { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] bytes = Encoding.UTF8.GetBytes(input); string result = BitConverter.ToString(md5.ComputeHash(bytes)); return result.Replace("-", ""); } return output; } /// /// 进行DES解密。 /// /// 要解密的串 /// 密钥,且必须为8位。 /// 已解密的字符串。 public static string DecryptDES(string source, string sKey) { byte[] inputByteArray = System.Convert.FromBase64String(source);//Encoding.UTF8.GetBytes(source); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Mode = CipherMode.ECB; des.Key = ASCIIEncoding.ASCII.GetBytes(sKey.Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey.Substring(0, 8)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return str; } } #endregion /// ///时间格式化 /// /// 返回字符串的类型(默认4) ///例子: 2014/05/08 19:14:17 ///type=1 2014/05/08 没有时分秒 ///type=2 2014/05/08 19:14 没有秒 ///type=3 14/05/08 19:14 没有年前两位和秒 ///type=4 05/08 19:14 没有年和秒 /// /// public static string ToUnityString(this DateTime dt, int type = 4) { if (dt == DateTime.MinValue) return ""; string formartStr = string.Empty; switch (type) { case 1: formartStr = "yyyy/MM/dd"; break; case 2: formartStr = "yyyy/MM/dd HH:mm"; break; case 3: formartStr = "yy/MM/dd HH:mm"; break; case 4: formartStr = "MM/dd HH:mm"; break; case 5: formartStr = "yyyyMM"; break; case 6: formartStr = "yyyy-MM-dd"; break; case 7: formartStr = "yyyy-MM-dd HH:mm:ss"; break; } return dt.ToString(formartStr); } /// ///时间格式化 /// /// 返回字符串的类型(默认4) ///例子: 2014/05/08 19:14:17 ///type=1 2014/05/08 没有时分秒 ///type=2 2014/05/08 19:14 没有秒 ///type=3 14/05/08 19:14 没有年前两位和秒 ///type=4 05/08 19:14 没有年和秒 /// /// public static string ToUnityString(this DateTime? dt, int type = 4) { if (dt == null || dt.Value == DateTime.MinValue) return ""; string formartStr = string.Empty; switch (type) { case 1: formartStr = "yyyy/MM/dd"; break; case 2: formartStr = "yyyy/MM/dd HH:mm"; break; case 3: formartStr = "yy/MM/dd HH:mm"; break; case 4: formartStr = "MM/dd HH:mm"; break; case 5: formartStr = "yyyyMM"; break; case 6: formartStr = "yyyy-MM-dd"; break; } return dt.Value.ToString(formartStr); } #region 枚举 public static string GetEnumName(int i) { string name = null; string[] names = Enum.GetNames(typeof(T)); if (i < names.Length) { name = names[i]; } return name; } public static string GetEnumNameByValue(int i) { string name = Enum.GetName(typeof(T), i); return name; } public static string GetCheckEnumNameByValue(int i) { string name = i.ToString(); if (Enum.IsDefined(typeof(T), i)) name = Enum.GetName(typeof(T), i); return name; } #endregion #region JSON public static T JSONToObject(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject(json); } public static string ConvertToJSON(IList list) { return Newtonsoft.Json.JsonConvert.SerializeObject(list); } public static string ConvertToJSON(T obj) { return Newtonsoft.Json.JsonConvert.SerializeObject(obj); } public static string ObjectToJson(T t) { return Newtonsoft.Json.JsonConvert.SerializeObject(t); } #endregion #region 十进制转六十四进制 static string[] SubstrSplit(string str, int lenStep) { if (string.IsNullOrEmpty(str)) return null; int L = str.Length % lenStep; if (L > 0) { for (int i = 0; i < lenStep - L; i++) { str = "0" + str; } } string tem = ""; while (str.Length >= lenStep) { if (str.Length > lenStep) tem += string.Format(",{0}", str.Substring(0, lenStep)); else tem += string.Format(",{0}", str); str = str.Substring(lenStep); } tem = tem.Trim(','); return tem.Split(','); } public static string Conver10To64Ext(long d10) { string str64 = ""; string[] fhs = "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".Split(','); string binStr = Convert.ToString(d10, 2); string[] bstrForLenStep = SubstrSplit(binStr, 6); if (bstrForLenStep == null) return ""; for (int j = 0; j < bstrForLenStep.Length; j++) { int index = Convert.ToInt32(bstrForLenStep[j], 2); str64 += string.Format("{0}", fhs[index]); } return str64; } #endregion #region unix 时间转换 /// /// 将Unix时间戳转换为DateTime类型时间 /// /// double 型数字 /// DateTime public static System.DateTime ConvertIntDateTime(double d) { System.DateTime time = System.DateTime.MinValue; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); time = startTime.AddSeconds(d); return time; } /// /// 将c# DateTime时间格式转换为Unix时间戳格式 /// /// 时间 /// double public static double ConvertDateTimeInt(System.DateTime time) { double intResult = 0; System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); intResult = (time - startTime).TotalSeconds; return intResult; } /// /// /// /// java长整型日期,毫秒为单位 /// public static DateTime JavaLongToDateTime(long timeJavaLong) { var dt1970 = new DateTime(1970, 1, 1, 0, 0, 0); var tricks1970 = dt1970.Ticks;//1970年1月1日刻度 var timeTricks = tricks1970 + timeJavaLong * 10000;//日志日期刻度 return new DateTime(timeTricks).AddHours(8);//转化为DateTime } #endregion #region 检查是否手机号 /// /// 00852+8位是香港的电话 /// /// /// public static bool ChekMobile(string number) { string rgs = @"^(13|14|15|17|18|0085)\d{9}$"; Regex reg = new Regex(rgs); return reg.IsMatch(number); } /// /// 检查是否包含手机号码 /// /// /// public static bool ContainMobile(string number) { string rgs = @".*(11|12|13|14|15|16|17|18|19)\d{9}.*"; Regex reg = new Regex(rgs); return reg.IsMatch(number); } /// /// 从文本中返回号码字符串 /// /// /// public static string GetMobile(string txt) { string rgs = @"(11|12|13|14|15|16|17|18|19)\d{9}"; string result = Regex.Match(txt, rgs).Value; return result; } public static bool CheckIsNum(string txt) { string rgs = "^\\d{6,16}$"; Regex reg = new Regex(rgs); return reg.IsMatch(txt); } public static bool IsNum(string txt) { string rgs = "^\\d+$"; Regex reg = new Regex(rgs); return reg.IsMatch(txt); } #endregion public static string NumberSub(string number) { string Sub_0 = @"^(013|015|016|018|014|017|019)\d*$"; Regex reg = new Regex(Sub_0); if (number.Length > 11 && reg.IsMatch(number)) return number.Substring(1); return number; } /// /// 验证固定电话号码 /// /// /// public static bool ValidateTelCode(string telcode) { string express = @"^(0[0-9]{2,3}\-?)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$"; return ValidateInput(telcode, express); } public static string NumberFormat(string number) { if (string.IsNullOrEmpty(number) || number.Length <= 6) { return number; } return number.Substring(0, 3) + new string('*', number.Length - 6) + number.Substring(number.Length - 3); } /// /// 验证固定电话号码无下滑斜杠 /// /// /// public static bool ValidateTelCode2(string telcode) { string express = @"^\d{6,20}$"; return ValidateInput(telcode, express); } /// /// 验证数据 /// /// 需验证数据 /// 正则表达式 /// 符合返回为true,否则返回false public static bool ValidateInput(string data, string express) { Regex reg = new Regex(express); return reg.IsMatch(data); } /// /// 获取随机数 /// /// /// public static string CreateRandomSatl(int codeCount) { string allChar = "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,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,w,x,y,z"; string[] allCharArray = allChar.Split(','); string randomCode = ""; int temp = -1; Random rand = new Random(); for (int i = 0; i < codeCount; i++) { if (temp != -1) { rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); } int t = rand.Next(50); if (temp == t) { return CreateRandomSatl(codeCount); } temp = t; randomCode += allCharArray[t]; } return randomCode; } public static string Sha512(string value) { SHA512 s512 = new SHA512Managed(); byte[] bit_pwd = Encoding.Default.GetBytes(value); byte[] bit_shapsw = s512.ComputeHash(bit_pwd); string shapsw = Convert.ToBase64String(bit_shapsw); return shapsw; } public static int PasswordStrength(string password) { if (string.IsNullOrWhiteSpace(password)) return -1; //字符统计 int iNum = 0, iLtt = 0, iSym = 0; foreach (char c in password) { if (c >= '0' && c <= '9') iNum++; else if (c >= 'a' && c <= 'z') iLtt++; else if (c >= 'A' && c <= 'Z') iLtt++; else iSym++; } if (password.Length < 6) return 3; //长度小于6的密码 if (iLtt == 0 && iSym == 0) return 1; //纯数字密码 if (iNum == 0 && iSym == 0) return 2; //纯字母密码 return 0; //正确 } public static string GetSendMsgModel(string strJson, string modelParam) { string key = string.Empty; string values = string.Empty; strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString(); Regex regex = new Regex(@"(?<={)[^}]+(?=})"); MatchCollection mc = regex.Matches(strJson); Dictionary list = new Dictionary(); for (int i = 0; i < mc.Count; i++) { string strRow = mc[i].Value; string[] strRows = strRow.Split('*'); foreach (string str in strRows) { string[] strCell = str.Split('#'); key = strCell[0].Replace("\"", ""); values = strCell[1].Replace("\"", ""); list.Add(key, values); } } foreach (var item in list) { modelParam = modelParam.Replace("${" + item.Key + "}", item.Value); } return modelParam; } public static string DateEnToCn(string date) { string datename = ""; date = date.ToLower(); switch (date) {//--Monday 周一 Tuesday 周二 Wednesday 周三 Thursday 周四 Friday 周五 Saturday 周六 Sunday 周日 case "monday": datename = "星期一"; break; case "tuesday": datename = "星期二"; break; case "wednesday": datename = "星期三"; break; case "thursday": datename = "星期四"; break; case "friday": datename = "星期五"; break; case "saturday": datename = "星期六"; break; case "sunday": datename = "星期日"; break; } return datename; } /// /// 将c# DateTime时间格式转换为Unix时间戳格式 /// /// 时间 /// long public static long ConvertDateTimeToInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); long t = (time.Ticks - startTime.Ticks) / 10000; //除10000调整为13位 return t; } /// /// 时间戳转为C#格式时间 /// /// /// public static DateTime ConvertStringToDateTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } /// /// 获取文件的MD5码 /// /// 传入的文件名(含路径及后缀名) /// public static string GetMD5HashFromFile(string fileName) { try { FileStream file = new FileStream(fileName, System.IO.FileMode.Open); MD5 md5 = new MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message); } } /// /// 查找指定目录下的所有末级子目录 /// /// 要查找的目录 /// 查找结果列表 /// 是否包含系统目录 /// 是否包含隐藏目录 public static void GetEndDirectories(DirectoryInfo dir, List list, bool system = false, bool hidden = false) { DirectoryInfo[] sub = dir.GetDirectories(); if (sub.Length == 0) {// 没有子目录了 list.Add(dir); return; } foreach (DirectoryInfo subDir in sub) { // 跳过系统目录 if (!system && (subDir.Attributes & FileAttributes.System) == FileAttributes.System) continue; // 跳过隐藏目录 if (!hidden && (subDir.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue; GetEndDirectories(subDir, list); } } /// /// 获取数据 /// /// /// /// public static string GetData(string Url, string RequestPara, Encoding encoding) { if (!String.IsNullOrEmpty(RequestPara)) RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara); WebRequest hr = HttpWebRequest.Create(Url + RequestPara); byte[] buf = encoding.GetBytes(RequestPara); hr.Method = "GET"; System.Net.WebResponse response = hr.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")); string ReturnVal = reader.ReadToEnd(); reader.Close(); response.Close(); return ReturnVal; } /// /// 获取数据 /// /// /// /// public static List GetArryData(string Url, string RequestPara, Encoding encoding) { if (!String.IsNullOrEmpty(RequestPara)) RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara); WebRequest hr = HttpWebRequest.Create(Url + RequestPara); byte[] buf = encoding.GetBytes(RequestPara); hr.Method = "GET"; List htmllist = new List(); System.Net.WebResponse response = hr.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { while (!reader.EndOfStream) { htmllist.Add(reader.ReadLine()); } } response.Close(); return htmllist; } /// /// 获取数据 /// /// /// /// public static string GetNewUrlData(string Url, string RequestPara, Encoding encoding) { if (!String.IsNullOrEmpty(RequestPara)) RequestPara = RequestPara.IndexOf('?') > -1 ? (RequestPara) : ("?" + RequestPara); WebRequest hr = HttpWebRequest.Create(Url + RequestPara); hr.Method = "GET"; System.Net.WebResponse response = hr.GetResponse(); string r= response.ResponseUri.AbsoluteUri; response.Close(); return r; } /// /// MD5 16位加密 加密后密码为小写 /// /// /// public static string GetMd5Str16(string ConvertString) { try { using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8); return t2.Replace("-", "").ToLower(); } } catch { return null; } } } }