using CsharpHttpHelper; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Caching; namespace Chat.Framework { /// /// Generates a 16 byte Unique Identification code of a computer /// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9 /// class FingerPrint { private static string fingerPrint = string.Empty; public static string Value() { if (string.IsNullOrEmpty(fingerPrint)) { fingerPrint = GetHash("CPU >> " + cpuId() + "|BIOS >> " + biosId() + "|BASE >> " + baseId() + "|DISK >> " + diskId() + "|VIDEO >> " + videoId() + "|MAC >> " + macId() ); } return fingerPrint; } private static string GetHash(string s) { MD5 sec = new MD5CryptoServiceProvider(); ASCIIEncoding enc = new ASCIIEncoding(); byte[] bt = enc.GetBytes(s); return GetHexString(sec.ComputeHash(bt)); } private static string GetHexString(byte[] bt) { string s = string.Empty; for (int i = 0; i < bt.Length; i++) { byte b = bt[i]; int n, n1, n2; n = (int)b; n1 = n & 15; n2 = (n >> 4) & 15; if (n2 > 9) s += ((char)(n2 - 10 + (int)'A')).ToString(); else s += n2.ToString(); if (n1 > 9) s += ((char)(n1 - 10 + (int)'A')).ToString(); else s += n1.ToString(); if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-"; } return s; } #region Original Device ID Getting Code //Return a hardware identifier private static string identifier (string wmiClass, string wmiProperty, string wmiMustBeTrue) { string result = ""; System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass); System.Management.ManagementObjectCollection moc = mc.GetInstances(); foreach (System.Management.ManagementObject mo in moc) { if (mo[wmiMustBeTrue].ToString() == "True") { //Only get the first one if (result == "") { try { result = mo[wmiProperty].ToString(); break; } catch { } } } } return result; } //Return a hardware identifier private static string identifier(string wmiClass, string wmiProperty) { string result = ""; System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass); System.Management.ManagementObjectCollection moc = mc.GetInstances(); foreach (System.Management.ManagementObject mo in moc) { //Only get the first one if (result == "") { try { result = mo[wmiProperty].ToString(); break; } catch { } } } return result; } private static string cpuId() { //Uses first CPU identifier available in order of preference //Don't get all identifiers, as it is very time consuming string retVal = identifier("Win32_Processor", "UniqueId"); if (retVal == "") //If no UniqueID, use ProcessorID { retVal = identifier("Win32_Processor", "ProcessorId"); if (retVal == "") //If no ProcessorId, use Name { retVal = identifier("Win32_Processor", "Name"); if (retVal == "") //If no Name, use Manufacturer { retVal = identifier("Win32_Processor", "Manufacturer"); } //Add clock speed for extra security retVal += identifier("Win32_Processor", "MaxClockSpeed"); } } return retVal; } //BIOS Identifier private static string biosId() { return identifier("Win32_BIOS", "Manufacturer") + identifier("Win32_BIOS", "SMBIOSBIOSVersion") + identifier("Win32_BIOS", "IdentificationCode") + identifier("Win32_BIOS", "SerialNumber") + identifier("Win32_BIOS", "ReleaseDate") + identifier("Win32_BIOS", "Version"); } //Main physical hard drive ID private static string diskId() { return identifier("Win32_DiskDrive", "Model") + identifier("Win32_DiskDrive", "Manufacturer") + identifier("Win32_DiskDrive", "Signature") + identifier("Win32_DiskDrive", "TotalHeads"); } //Motherboard ID private static string baseId() { return identifier("Win32_BaseBoard", "Model") + identifier("Win32_BaseBoard", "Manufacturer") + identifier("Win32_BaseBoard", "Name") + identifier("Win32_BaseBoard", "SerialNumber"); } //Primary video controller ID private static string videoId() { return identifier("Win32_VideoController", "DriverVersion") + identifier("Win32_VideoController", "Name"); } //First enabled network card ID private static string macId() { return identifier("Win32_NetworkAdapterConfiguration", "MACAddress", "IPEnabled"); } #endregion } /// /// 工具类 /// internal class Util { /// /// 设置缓存 /// /// /// /// /// public static bool SetCache(string text, int seconds = 30) { try { Cache cache = HttpRuntime.Cache; //查找 md5 的缓存,不存在则返回null object item = cache[text]; if (item == null) cache.Insert(text, 1, null, DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration); return true; } catch (Exception ex) { } return false; } /// /// 缓存是否存在 /// /// /// /// /// public static bool GetCache(string text) { try { Cache cache = HttpRuntime.Cache; object item = cache[text]; return item != null ? true : false; } catch (Exception) { } return false; } /// /// [解析] /// 类型=转账,新好友,新申请,新群友,群消息,私消息,图片,视频,取群成员 /// private static List NoAnalysisConfig = null; public static List GetNoAnalysisConfig() { try { if (NoAnalysisConfig == null) { IniHelper ini = new IniHelper(Util.MapFile("系统配置.ini", "Config")); var tmp = ini.GetValue("解析", "类型"); if (!string.IsNullOrWhiteSpace(tmp)) NoAnalysisConfig = tmp.Replace(",", ",").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(f => f.Trim()).ToList(); else NoAnalysisConfig = new List(); } } catch (Exception ex) { } return NoAnalysisConfig; } /// /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件 /// /// /// public static Bitmap ReadImageFile(string path) { //OpenRead Image result = null; try { using (FileStream fs = File.OpenRead(path)) { int filelength = 0; filelength = (int)fs.Length; //获得文件长度 Byte[] image = new Byte[filelength]; //建立一个字节数组 fs.Read(image, 0, filelength); //按字节流读取 result = Image.FromStream(fs); return new Bitmap(result); } } catch (Exception) { } return null; } /// /// 将图片控制在宽度为指定的像素 /// /// /// /// public static Bitmap PercentImage(Image srcImage, int size = 200) { int newW = srcImage.Width < size ? srcImage.Width : size; int newH = int.Parse(Math.Round(srcImage.Height * (double)newW / srcImage.Width).ToString()); try { Bitmap b = new Bitmap(newW, newH); Graphics g = Graphics.FromImage(b); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default; g.DrawImage(srcImage, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel); g.Dispose(); return b; } catch (Exception) { return null; } } /// /// 将图片按百分比压缩, /// /// /// /// flag取值1到100,越小压缩比越大 /// public static bool YaSuo(Image iSource, string outPath, int flag = 80) { ImageFormat tFormat = iSource.RawFormat; EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag; EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) iSource.Save(outPath, jpegICIinfo, ep); else iSource.Save(outPath, tFormat); return true; } catch { return false; } iSource.Dispose(); } public static string GetMD5Hash(byte[] bytedata) { try { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(bytedata); 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("GetMD5Hash() fail,error:" + ex.Message); } } public static string RemoveEmoji(string text) { if (string.IsNullOrWhiteSpace(text)) return string.Empty; if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["RemoveWechatEmoji"]) && System.Configuration.ConfigurationManager.AppSettings["RemoveWechatEmoji"].ToUpper() == "FALSE") { return text; } text = Regex.Replace(text, @"\%uD.{3}", ""); text = Regex.Replace(text, "[👃☺️☹️☠️✊✌️☝✋✍️♀️♂️]", ""); foreach (var a in text) { byte[] bts = Encoding.UTF32.GetBytes(a.ToString()); if (bts[0].ToString() == "253" && bts[1].ToString() == "255") { text = text.Replace(a.ToString(), ""); } } return text; } /// /// 壓縮圖片 /// /// 圖片流 /// 壓縮質量0-100之間 數值越大質量越高 /// public static byte[] CompressionImage(Stream fileStream, long quality) { try { using (Image img = Image.FromStream(fileStream)) { using (Bitmap bitmap = new Bitmap(img)) { ImageCodecInfo CodecInfo = GetEncoder(img.RawFormat); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, quality); myEncoderParameters.Param[0] = myEncoderParameter; using (MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, CodecInfo, myEncoderParameters); myEncoderParameters.Dispose(); myEncoderParameter.Dispose(); return ms.ToArray(); } } } } catch (Exception) { return null; } } #region /// /// 获取表示JPEG编解码器的ImageCodecInfo对象。 /// /// /// private static ImageCodecInfo GetEncoderInfo(String mimeType) { int j; ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } /// /// 图片压缩(降低质量以减小文件的大小) /// /// 传入的Bitmap对象 /// 压缩后的Stream对象 /// 压缩等级,0到100,0 最差质量,100 最佳 public static void Compress(Bitmap srcBitmap, Stream destStream, long level) { try { ImageCodecInfo myImageCodecInfo; System.Drawing.Imaging.Encoder myEncoder; EncoderParameter myEncoderParameter; EncoderParameters myEncoderParameters; // 获取表示JPEG编解码器的ImageCodecInfo对象。 myImageCodecInfo = GetEncoderInfo("image/jpeg"); //基于质量参数类别的GUID创建编码器对象。 myEncoder = System.Drawing.Imaging.Encoder.Quality; // 创建EncoderParameters对象。EncoderParameters对象有一个EncoderParameter.objects数组。在这种情况下,只有一个。数组中的EncoderParameter对象。 myEncoderParameters = new EncoderParameters(1); // 将位图保存为一个JPEG文件给定的质量水平 myEncoderParameter = new EncoderParameter(myEncoder, level); myEncoderParameters.Param[0] = myEncoderParameter; srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters); } catch (Exception ex) { throw ex; } } /// /// 图片压缩(降低质量以减小文件的大小) /// /// 传入的Bitmap对象 /// 压缩后的图片保存路径 /// 压缩等级,0到100,0 最差质量,100 最佳 public static void Compress(Bitmap srcBitMap, string destFile, long level) { try { Stream s = new FileStream(destFile, FileMode.Create); Compress(srcBitMap, s, level); s.Close(); } catch (Exception ex) { throw ex; } } #endregion private static ImageCodecInfo GetEncoder(ImageFormat format) { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); foreach (ImageCodecInfo codec in codecs) { if (codec.FormatID == format.Guid) { return codec; } } return null; } public static string GenerateRandomCode(int number) { StringBuilder sb = new StringBuilder(); Random r = new Random(); for (int i = 0; i < number; i++) { sb.Append(r.Next(0, 9)); } return sb.ToString(); } public static int ReadInt(byte[] buf, int index) { if (buf.Length >= 16) { var seqBuf = new byte[4]; Buffer.BlockCopy(buf, index, seqBuf, 0, 4); return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(seqBuf, 0)); } return 1; } public static Dictionary ConvertJsonToDic(string str) { try { System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var json = serializer.Deserialize>(str); return json; } catch { } return null; } public static string ObjectToJson(object obj) { string result; try { System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); jss.MaxJsonLength = Int32.MaxValue; result = jss.Serialize(obj); } catch (Exception ex) { result = ex.Message; } return result; } public static int TimeStamp() { DateTime time = DateTime.Now.ToUniversalTime(); DateTime time2 = new DateTime(0x7b2, 1, 1); return (int)time.Subtract(time2).TotalSeconds; } public static string MapPath(string path = "", bool CreateDirectory = true) { if (string.IsNullOrWhiteSpace(path)) { return System.Windows.Forms.Application.StartupPath.ToString() + "\\"; } path = Path.Combine(System.Windows.Forms.Application.StartupPath.ToString() + "\\", path); if (!(!CreateDirectory || Directory.Exists(path))) { Directory.CreateDirectory(path); } return path; } public static string MapFile(string file, string path = "") { return Path.Combine(MapPath(path, true), file); } public static T ConvertJsonToObj(string str) { System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var json = serializer.Deserialize(str); return json; } public static string HexToStr(byte[] bytes) { //string returnStr = ""; //if (bytes != null) //{ // for (int i = 0; i < bytes.Length; i++) // { // returnStr += bytes[i].ToString("X2"); // } //} //return returnStr; StringBuilder returnStr = new StringBuilder(""); if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { returnStr.Append(bytes[i].ToString("X2")); } } return returnStr.ToString(); } public static byte[] StrToHex(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) { hexString = hexString + " "; } byte[] buffer = new byte[hexString.Length / 2]; for (int i = 0; i < buffer.Length; i++) { buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 0x10); } return buffer; } /// /// 是否能 Ping 通指定的主机 /// /// ip 地址或主机名或域名 /// true 通,false 不通 public static bool Ping(string ip) { return true; try { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; string data = "Test Data!"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 1000; // Timeout 时间,单位:毫秒 System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) return true; else return false; } catch (Exception) { return false; } } public void WriteLog(string msg, string src) { try { using (StreamWriter sw = File.AppendText(src)) { sw.WriteLine("消息:" + msg); sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); sw.WriteLine("**************************************************"); sw.WriteLine(); sw.Flush(); sw.Close(); sw.Dispose(); } } catch { } } public static string GetComputerMD5() { string info = FingerPrint.Value() + Dns.GetHostName(); return MD5Encrypt(info, Encoding.UTF8); } /// /// MD5加密 /// /// 需要加密的字符串 /// public static string MD5Encrypt(string input) { return MD5Encrypt(input, new UTF8Encoding()); } public static int GetTimeTotalSeconds() { return GetTimeTotalSeconds(DateTime.Now); } public static List GetRandomList(List inputList) { //Copy to a array T[] copyArray = new T[inputList.Count]; inputList.CopyTo(copyArray); //Add range List copyList = new List(); copyList.AddRange(copyArray); //Set outputList and random List outputList = new List(); Random rd = new Random(DateTime.Now.Millisecond); while (copyList.Count > 0) { //Select an index and item int rdIndex = rd.Next(0, copyList.Count - 1); T remove = copyList[rdIndex]; //remove it from copyList and add it to output copyList.Remove(remove); outputList.Add(remove); } return outputList; } public static string GetPublicIpAdress() { try { return "127.0.0.1"; string html = new WebClient().DownloadString("http://ip.chinaz.com"); var reg = Regex.Match(html, "
(.*?)
"); if (reg.Success) { return reg.Groups[1].Value; } } catch (Exception) { } return string.Empty; } public static int GetTimeTotalSeconds(DateTime datetime) { DateTime time = datetime.ToUniversalTime(); DateTime time2 = new DateTime(0x7b2, 1, 1); return (int)time.Subtract(time2).TotalSeconds; } /// /// 域名转换为IP地址 /// /// 域名或IP地址 /// IP地址 public static string Hostname2ip(string hostname) { try { IPAddress ip; if (IPAddress.TryParse(hostname, out ip)) return ip.ToString(); else return Dns.GetHostEntry(hostname).AddressList[0].ToString(); } catch (Exception) { throw new Exception("IP Address Error"); } } /// /// MD5加密 /// /// 需要加密的字符串 /// 字符的编码 /// public static string MD5Encrypt(string input, Encoding encode) { if (string.IsNullOrEmpty(input)) { return null; } MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); byte[] data = md5Hasher.ComputeHash(encode.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } /// /// 文件转换成Base64字符串 /// /// 文件绝对路径 /// public static String FileToBase64(string fileName) { string strRet = ""; try { FileStream fs = new FileStream(fileName, FileMode.Open); byte[] bt = new byte[fs.Length]; fs.Read(bt, 0, bt.Length); strRet = Convert.ToBase64String(bt); fs.Close(); } catch (Exception ex) { strRet = null; } return strRet; } /// /// Base64字符串转换成文件 /// /// base64字符串 /// 保存文件的绝对路径 /// public static bool Base64ToFileAndSave(string strInput, string fileName) { bool bTrue = false; try { byte[] buffer = Convert.FromBase64String(strInput); FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate); fs.Write(buffer, 0, buffer.Length); fs.Close(); bTrue = true; } catch (Exception ex) { } return bTrue; } } public static class FileTools { /// /// 图片下载 /// /// /// public static Image DownloadImage(string url, string path) { for (int i = 0; i < 4; i++) { if (i < 2) { try { WebClient mywebclient = new WebClient(); byte[] Bytes = mywebclient.DownloadData(url); using (MemoryStream ms = new MemoryStream(Bytes)) { Image outputImg = Image.FromStream(ms); outputImg.Save(path); return outputImg; } } catch (Exception ex) { } } else { try { var http = new HttpHelper(); var item = http.GetItem(url); item.ReadWriteTimeout = 10000; var image = http.GetImage(item); image.Save(path); return image; } catch (Exception ex) { } } } return null; } /// /// 文件MD5校验 /// /// /// public static string GetMD5Hash(string pathName) { string strResult = ""; string strHashData = ""; byte[] arrbytHashValue; FileStream oFileStream = null; MD5CryptoServiceProvider oMD5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider(); try { oFileStream = new FileStream(pathName, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite); arrbytHashValue = oMD5Hasher.ComputeHash(oFileStream);//计算指定Stream 对象的哈希值                 oFileStream.Close();                 //由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”                 strHashData = BitConverter.ToString(arrbytHashValue);                 //替换-                 strHashData = strHashData.Replace("-", ""); strResult = strHashData; } catch (System.Exception ex) { } return strResult; } /// /// 设置缓存 /// /// /// /// /// public static bool SetCacheObj(string k, object v, int m = 10) { try { Cache cache = HttpRuntime.Cache; //查找 md5 的缓存,不存在则返回null object item = cache[k]; if (item == null) cache.Insert(k, v, null, DateTime.Now.AddMinutes(m), System.Web.Caching.Cache.NoSlidingExpiration); return true; } catch (Exception ex) { } return false; } /// /// 缓存是否存在 /// /// /// /// /// public static object GetCacheObj(string k) { try { Cache cache = HttpRuntime.Cache; return cache[k]; } catch (Exception) { } return null; } } }