using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using ConsoleHttp.Model; namespace MqttMsgServer.Tools { public static class StringHelper { /// /// MD5字符串加密 /// /// /// 加密后字符串 public static string GenerateMD5(string txt) { using (MD5 mi = MD5.Create()) { byte[] buffer = Encoding.Default.GetBytes(txt); //开始加密 byte[] newBuffer = mi.ComputeHash(buffer); StringBuilder sb = new StringBuilder(); for (int i = 0; i < newBuffer.Length; i++) { sb.Append(newBuffer[i].ToString("x2")); } return sb.ToString(); } } /// /// MD5流加密 /// /// /// public static string GenerateMD5(Stream inputStream) { using (MD5 mi = MD5.Create()) { //开始加密 byte[] newBuffer = mi.ComputeHash(inputStream); StringBuilder sb = new StringBuilder(); for (int i = 0; i < newBuffer.Length; i++) { sb.Append(newBuffer[i].ToString("x2")); } return sb.ToString(); } } public static ResponseResult CheckError(string errorMsg, int returnCode = 9001) { ResponseResult result = new ResponseResult {IsSuccess = false, ErrorMessage = errorMsg, ReturnCode = 9001}; return result; } /// /// Base64 编码 /// /// 编码方式 /// 要编码的字符串 /// 返回编码后的字符串 public static string EncodeBase64(this string source, Encoding encode = null) { string result; try { encode = encode ?? Encoding.UTF8; byte[] bytes = encode.GetBytes(source); result = Convert.ToBase64String(bytes); } catch { result = source; } return result; } /// /// Base64 解码 /// /// 解码方式 /// 要解码的字符串 /// 返回解码后的字符串 public static string DecodeBase64(this string source, Encoding encode = null) { string result; try { byte[] bytes = Convert.FromBase64String(source); encode = encode ?? Encoding.UTF8; result = encode.GetString(bytes); } catch { result = source; } return result; } public static int ToInt(this string s, int defaultValue = 0) { int i; return int.TryParse(s, out i) ? i : defaultValue; } public static List ToList(DataTable dt) where T : class, new() { Type t = typeof(T); PropertyInfo[] propertyInfo = t.GetProperties(); List list = new List(); foreach (DataRow item in dt.Rows) { T obj = new T(); foreach (PropertyInfo s in propertyInfo) { var typeName = s.Name; if (dt.Columns.Contains(typeName)) { if (!s.CanWrite) continue; object value = item[typeName]; if (value == DBNull.Value) continue; s.SetValue(obj, s.PropertyType == typeof(string) ? value.ToString() : value, null); } } list.Add(obj); } return list; } } public static class ExtendEnum { public static int ToInt(this System.Enum e) { return e.GetHashCode(); } } }