using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Drawing.Imaging; using System.Net; using System.Drawing.Drawing2D; using System.Xml; using System.Collections; namespace xxxxxxx { public class Common {
/// <summary> /// 隐藏文字 /// </summary> /// <param name="name"></param> /// <param name="showcount">显示首尾几位</param> /// 例子:HideName("13912345678",3)=> 139*****678 /// <returns></returns> public static string HideString(string name, int showcount = 1) { string str = ""; Func<int, string> go = (num) => { string s = ""; for (int i = 0; i < num; i++) { s += "*"; } return s; }; switch (name.Length) { case 0: case 1: str = name; break; case 2: str = "*" + name.Substring(1); break; default: str = name.Substring(0, showcount) + go(name.Length - (showcount * 2)) + name.Substring(name.Length - showcount); break; } return str; }
/// <summary> /// 序号添0补充 /// </summary> /// <param name="num">序号</param> /// <param name="length">序号长度</param> /// generate_number(123,5)=>00123 /// <returns></returns> public static string generate_number(int num, int length = 5) { //如果序号长度大于长度 默认为数字长度 if (num.ToString().Length > length) { length = num.ToString().Length; } string strs = ""; for (int i = 0; i < length - num.ToString().Length; i++) strs += "0"; return strs + num.ToString(); }
/// <summary> /// 获取ip /// </summary> /// <param name="context"></param> /// <returns></returns> public static string GetIP(HttpContext context) { string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(result)) { result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } if (string.IsNullOrEmpty(result)) { result = HttpContext.Current.Request.UserHostAddress; } if (string.IsNullOrEmpty(result)) { return "0.0.0.0"; } return result; }
/// <summary> /// Object转换String /// </summary> /// <param name="session"></param> /// <returns></returns> public static string ObjectToString(object session) { return session == null ? "" : session.ToString(); } /// <summary> /// Object转换Int /// </summary> /// <param name="session"></param> /// <returns></returns> public static int ObjectToInt(object session) { int num = -1; int.TryParse(session == null ? "" : session.ToString(), out num); return num; }
/// <summary> /// Object转换Int /// </summary> /// <param name="session"></param> /// <param name="mr">默认-1</param> /// <returns></returns> public static int ObjectToInt(object session, int mr = -1) { int num = mr; if (session == null) return num; int.TryParse(session.ToString(), out num); return num; }
/// <summary> /// Object转换Decimal /// </summary> /// <param name="session"></param> /// <returns></returns> public static decimal ObjectToDecimal(object session) { decimal num = -1; decimal.TryParse(session == null ? "" : session.ToString(), out num); return num; } /// <summary> /// Object转换DateTime 时间格式转换 时间格式错误|默认1970-01-01 /// </summary> /// <param name="session"></param> /// <returns></returns> public static DateTime ObjectToDateTime(object session) { DateTime num = DateTime.Parse("1970-01-01"); DateTime.TryParse(session == null ? null : session.ToString(), out num); return num; } /// <summary> /// Object转换Bool /// </summary> /// <param name="session"></param> /// <returns></returns> public static bool ObjectToBool(object session) { bool buf = false; bool.TryParse(session == null ? "" : session.ToString(), out buf); return buf; } /// <summary> /// 图片转Base64 /// </summary> /// <param name="imagefile"></param> /// <returns></returns> public static string GetBase64FromImage(string imagefile) { string strbaser64 = ""; try { Bitmap bmp = new Bitmap(imagefile); strbaser64 = GetBase64FromImage(bmp).base64; } catch (Exception) { throw new Exception("Something wrong during convert!"); } return strbaser64; } /// <summary> /// 图片转Base64 /// </summary> /// <param name="bmp"></param> /// <returns></returns> public static Base64Class GetBase64FromImage(Bitmap bmp) { Base64Class base64Class = new Base64Class(); try { MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); base64Class.base64 = Convert.ToBase64String(arr); base64Class.width = bmp.Width; base64Class.height = bmp.Height; } catch (Exception) { throw new Exception("Something wrong during convert!"); } return base64Class; } public class Base64Class { /// <summary> /// 图片base64 /// </summary> public string base64 { get; set; } /// <summary> /// 宽 /// </summary> public int width { get; set; } /// <summary> /// 高 /// </summary> public int height { get; set; } } /// <summary> /// Base64 转 图片 /// </summary> /// <param name="base64string"></param> /// <returns></returns> public static Bitmap GetImageFromBase64(string base64string) { byte[] b = Convert.FromBase64String(base64string); MemoryStream ms = new MemoryStream(b); Bitmap bitmap = new Bitmap(ms); return bitmap; } /// <summary> /// Base64 转 流 /// </summary> /// <param name="base64string"></param> /// <returns></returns> public static MemoryStream Base64ToMemo(string base64string) { byte[] b = Convert.FromBase64String(base64string); MemoryStream ms = new MemoryStream(b); ms.Position = 0; return ms; } /// <summary> /// 将 Stream 转成 byte[] /// </summary> /// <param name="stream"></param> /// <returns></returns> public static byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } /// <summary> /// 递归删除 文件 文件夹 /// </summary> /// <param name="directoryUrl"></param> public static void RecursiveDel(string directoryUrl) { if (Directory.Exists(directoryUrl)) { //当前目录所有文件 foreach (var file in Directory.GetFiles(directoryUrl)) if (File.Exists(file)) File.Delete(file); //当前目录中所有目录 //递归删除 foreach (var dire in Directory.GetDirectories(directoryUrl)) RecursiveDel(dire); Directory.Delete(directoryUrl); } } /// <summary> /// DateTime时间格式转换为Unix时间戳格式 /// </summary> /// <param name="time"> DateTime时间格式</param> /// <returns>Unix时间戳格式</returns> public static int ConvertDateTimeInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; } /// <summary> /// 判断UserAgent设备 /// </summary> /// <param name="ua"></param> /// <returns></returns> public static string CheckAnget(string ua) { string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" }; string[] pckeyword = { "Windows NT", "Macintosh" }; if (ua.Contains("Windows NT")) { //return "Windows"; return "PC"; } else if (ua.Contains("Macintosh")) { //return "OS X"; return "苹果"; } else { foreach (var item in keywords) { if (ua.Contains(item)) { //return item; return "手机"; } } } return ua; } /// <summary> /// 保留几位小数取小数点 非四舍五入 /// </summary> /// <returns></returns> public static decimal DecimalPointNotRound(object num, int count = 2) { decimal _n = 0; if (!decimal.TryParse(num.ToString(), out _n)) return _n; Regex re = new Regex(@"-?d*(.d{" + count + "})?"); var match = re.Match(num.ToString()); return decimal.Parse(match.Value); } ///移除HTML标签 /// <summary> /// 移除HTML标签 /// </summary> /// <param name="HTMLStr">HTMLStr</param> public static string ParseTags(string HTMLStr) { return System.Text.RegularExpressions.Regex.Replace(HTMLStr, "<[^>]*>", ""); } /// 取出文本中的图片地址 /// 取出文本中的图片地址 /// <summary> /// 取出文本中的图片地址 /// </summary> /// <param name="HTMLStr">HTMLStr</param> public static string GetImgUrl(string HTMLStr) { string str = string.Empty; string sPattern = @"^<imgs+[^>]*>"; Regex r = new Regex(@"<imgs+[^>]*s*srcs*=s*([']?)(?<url>S+)'?[^>]*>", RegexOptions.Compiled); Match m = r.Match(HTMLStr.ToLower()); if (m.Success) str = m.Result("${url}"); return str; } /// <summary> /// 加密 /// </summary> /// <param name="pToEncrypt"></param> /// <param name="sKey">密钥必须是8位</param> /// <returns></returns> public static string MD5Encrypt(string pToEncrypt, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString(); } /// <summary> /// 解密 /// </summary> /// <param name="pToDecrypt"></param> /// <param name="sKey"></param> /// <returns></returns> public static string MD5Decrypt(string pToDecrypt, string sKey) { string text = ""; try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; for (int x = 0; x < pToDecrypt.Length / 2; x++) { int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); text = System.Text.Encoding.Default.GetString(ms.ToArray()); } catch { text = pToDecrypt; } return text; } /// <summary> /// 加密 /// </summary> /// <param name="toEncrypt">要加密的字符串,即明文</param> /// <param name="key">公共密钥</param> /// <param name="useHashing">是否使用MD5生成机密秘钥</param> /// <returns>加密后的字符串,即密文</returns> public static string Encrypt(string toEncrypt, string key, bool useHashing) { try { byte[] keyArray; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } catch { } return string.Empty; } /// <summary> /// 解密 /// </summary> /// <param name="toDecrypt">要解密的字符串,即密文</param> /// <param name="key">公共密钥</param> /// <param name="useHashing">是否使用MD5生成机密密钥</param> /// <returns>解密后的字符串,即明文</returns> public static string Decrypt(string toDecrypt, string key, bool useHashing) { try { byte[] keyArray; byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); tdes.Key = keyArray; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return UTF8Encoding.UTF8.GetString(resultArray); } catch { } return string.Empty; } /// <summary> /// 删除文本中的图片 /// </summary> /// <param name="content"></param> public static void DeleteContentImg(string content) { var matches = Regex.Matches(content, @"<img[^<>]*?src[s ]*=[s ]*[""']?[s ]*(?<imgUrl>[^s ""'<>]*)[^<>]*?/?[s ]*>"); foreach (Match match in matches) { string imgpath = match.Groups["imgUrl"].Value; } } /// <summary> /// 图片缩放 /// </summary> /// <param name="b"></param> /// <param name="destHeight"></param> /// <param name="destWidth"></param> /// <returns></returns> public static Bitmap ImgThumbnail(Bitmap b, int destHeight, int destWidth) { System.Drawing.Image imgSource = b; System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat; int sW = 0, sH = 0; // 按比例缩放 int sWidth = imgSource.Width; int sHeight = imgSource.Height; if (sHeight > destHeight || sWidth > destWidth) { if ((sWidth * destHeight) > (sHeight * destWidth)) { sW = destWidth; sH = (destWidth * sHeight) / sWidth; } else { sH = destHeight; sW = (sWidth * destHeight) / sHeight; } } else { sW = sWidth; sH = sHeight; } Bitmap outBmp = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage(outBmp); g.Clear(Color.Transparent); // 设置画布的描绘质量 g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel); g.Dispose(); // 以下代码为保存图片时,设置压缩质量 EncoderParameters encoderParams = new EncoderParameters(); long[] quality = new long[1]; quality[0] = 100; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; imgSource.Dispose(); return outBmp; } /// <summary> /// 下载文件 /// </summary> /// <param name="url"></param> /// <returns></returns> public static MemoryStream DownloadFile(string url) { Uri uri = new Uri(url.Replace("\", "/")); WebRequest request = WebRequest.Create(uri); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); MemoryStream ms = new MemoryStream(); Byte[] buffer = new Byte[1024]; int current = 0; while ((current = stream.Read(buffer, 0, buffer.Length)) != 0) { ms.Write(buffer, 0, current); } return ms; } /// <summary> /// 下载图片 /// </summary> /// <param name="url"></param> /// <returns></returns> public static Bitmap DownloadImg(string url) { Bitmap bit = null; try { Uri uri = new Uri(url.Replace("\", "/")); WebRequest request = WebRequest.Create(uri); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); MemoryStream ms = new MemoryStream(); Byte[] buffer = new Byte[1024]; int current = 0; while ((current = stream.Read(buffer, 0, buffer.Length)) != 0) { ms.Write(buffer, 0, current); } bit = new Bitmap(ms); } catch { } return bit; } /// <summary> /// 剪裁 -- 用GDI+ /// </summary> /// <param name="b">原始Bitmap</param> /// <param name="StartX">开始坐标X</param> /// <param name="StartY">开始坐标Y</param> /// <param name="iWidth">宽度</param> /// <param name="iHeight">高度</param> /// <returns>剪裁后的Bitmap</returns> public static Bitmap Cut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight) { if (b == null) { return null; } int w = b.Width; int h = b.Height; if (StartX >= w || StartY >= h) { return null; } if (StartX + iWidth > w) { iWidth = w - StartX; } if (StartY + iHeight > h) { iHeight = h - StartY; } try { Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(bmpOut); Rectangle destRect = new Rectangle(0, 0, iWidth, iHeight);//显示图像的位置 Rectangle srcRect = new Rectangle(StartX, StartY, iWidth, iHeight);//显示图像那一部分 GraphicsUnit units = GraphicsUnit.Pixel;//源矩形的度量单位设置为像素 g.DrawImage(b, destRect, srcRect, units); g.Dispose(); return bmpOut; } catch { return null; } } /// <summary> /// 图片剪切 /// </summary> /// <param name="bit"></param> /// <param name="iWidth"></param> /// <param name="iHeight"></param> /// <param name="StartX">偏移X</param> /// <param name="StartY">偏移Y</param> /// <returns></returns> public static Bitmap BitmapCut(Bitmap bit, int iWidth = 100, int iHeight = 100, int StartX = 0, int StartY = 0) { int sWidth = iWidth; int sHeight = iHeight; if (bit.Width > bit.Height) //宽处理 { int w = int.Parse(((bit.Width / (double)bit.Height) * iHeight).ToString("0")); if (w > iWidth) sWidth = w; else sHeight = int.Parse((iHeight / (bit.Width / (double)bit.Height)).ToString("0")); } else if (bit.Height > bit.Width) { int h = int.Parse(((bit.Height / (double)bit.Width * bit.Width)).ToString("0")); if (h > iHeight) sHeight = h; } int strY = ((bit.Height - iHeight) / 2) + StartY; int strX = ((bit.Width - iWidth) / 2) + StartX; bit = Common.Cut(bit, strX, strY, iWidth, iHeight); return bit; } /// <summary> /// 图片缩略图 /// </summary> /// <param name="bit"></param> /// <param name="iWidth"></param> /// <param name="iHeight"></param> /// <param name="StartX">偏移X</param> /// <param name="StartY">偏移Y</param> /// <returns></returns> public static Bitmap BitmapThumbnail(Bitmap bit, int iWidth = 100, int iHeight = 100, int StartX = 0, int StartY = 0) { int sWidth = iWidth; int sHeight = iHeight; if (bit.Width > bit.Height) //宽处理 { int w = int.Parse(((bit.Width / (double)bit.Height) * iHeight).ToString("0")); if (w > iWidth) sWidth = w; else sHeight = int.Parse((iHeight / (bit.Width / (double)bit.Height)).ToString("0")); } else if (bit.Height > bit.Width) { int h = int.Parse(((bit.Height / (double)bit.Width * bit.Width)).ToString("0")); if (h > iHeight) sHeight = h; } int strY = ((bit.Height - iHeight) / 2) + StartY; int strX = ((bit.Width - iWidth) / 2) + StartX; bit = Common.Cut(bit, strX, strY, iWidth, iHeight); return bit; } /// <summary> /// int获取枚举 /// </summary> /// <typeparam name="T">枚举集合</typeparam> /// <param name="num"></param> /// <returns></returns> public static T NumToEnum<T>(int num) { foreach (var myCode in Enum.GetValues(typeof(T))) { if ((int)myCode == num) { return (T)myCode; } } throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", num), "Description"); } /// <summary> /// 获取一个类指定的属性值 /// </summary> /// <param name="info">object对象</param> /// <param name="field">属性名称</param> /// <returns></returns> public static object GetPropertyValue(object info, string field) { if (info == null) return null; Type t = info.GetType(); IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi; return property.First().GetValue(info, null); } static int GetRandomSeed() { byte[] bytes = new byte[4]; System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); } /// <summary> /// 随意数 /// </summary> /// <param name="num">随机数位数</param> /// <returns></returns> public static string GetRandomNum(int num) { StringBuilder str = new StringBuilder(); Random rand = new Random(GetRandomSeed()); for (int i = 0; i < num; i++) { str.Append(rand.Next(0, 9).ToString()); } return str.ToString(); } /// <summary> /// 随机数(带英文) /// </summary> /// <param name="Length"></param> /// <returns></returns> public static string GenerateRandom(int Length) { 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','p','q','r','s','t','u','v','w','x','y','z' }; System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62); Random rd = new Random(); for (int i = 0; i < Length; i++) { newRandom.Append(constant[rd.Next(constant.Length)]); } return newRandom.ToString(); } public static string HttpPost2(string Url, string postDataStr, string contentType = "application/x-www-form-urlencoded") { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.Timeout = 20000; request.KeepAlive = true; request.ContentType = contentType; request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"; byte[] postData = System.Text.Encoding.GetEncoding("gb2312").GetBytes(postDataStr); request.ContentLength = postData.Length; //request.CookieContainer = cookie; Stream myRequestStream = request.GetRequestStream(); //Stream myStreamWriter = new Stream(request.GetRequestStream(), Encoding.GetEncoding("gb2312")); myRequestStream.Write(postData, 0, postData.Length); myRequestStream.Close(); //myStreamWriter.Flush(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //response.Cookies = cookie.GetCookies(response.ResponseUri); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } /// <summary> /// 间隔时间 刚刚 几分钟前..... /// </summary> /// <param name="date"></param> /// <returns></returns> public static string TimeInterval(DateTime date) { string time = ""; var dq = DateTime.Now; var timespan = dq - date; var day = timespan.TotalDays; if (timespan.TotalMinutes < 1) { time = "刚刚"; } else if (timespan.TotalHours < 1) { time = timespan.TotalMinutes.ToString("0") + "分钟前"; } else if (timespan.TotalDays < 1) { time = timespan.TotalHours.ToString("0") + "小时前"; } else if (timespan.TotalDays < 2) { time = "昨天"; } else if (timespan.TotalDays < 3) { time = "前天"; } else if (dq.Year - date.Year <= 0) { time = date.ToString("MM月dd日"); } else if (dq.Year - date.Year > 0) { time = date.ToString("yyyy年MM月dd日"); } else { time = date.ToString(); } return time; } /// <summary> /// 传入URL返回网页的html代码 /// </summary> /// <param name="Url">URL</param> /// <returns></returns> public static string getUrltoHtml(string Url) { string errorMsg = ""; try { System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); // Get the response instance. System.Net.WebResponse wResp = wReq.GetResponse(); // Read an HTTP-specific property //if (wResp.GetType() ==HttpWebResponse) //{ //DateTime updated =((System.Net.HttpWebResponse)wResp).LastModified; //} // Get the response stream. System.IO.Stream respStream = wResp.GetResponseStream(); // Dim reader As StreamReader = New StreamReader(respStream) System.IO.StreamReader reader = new System.IO.StreamReader(respStream, System.Text.Encoding.GetEncoding("gb2312")); return reader.ReadToEnd(); } catch (System.Exception ex) { errorMsg = ex.Message; } return ""; } /// <summary> /// 类赋值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="pTargetObjSrc"></param> /// <param name="pTargetObjDest"></param> public static void EntityToEntity<T>(T pTargetObjSrc, T pTargetObjDest) { try { foreach (var mItem in typeof(T).GetProperties()) { mItem.SetValue(pTargetObjDest, mItem.GetValue(pTargetObjSrc, new object[] { }), null); } } catch (NullReferenceException NullEx) { throw NullEx; } catch (Exception Ex) { throw Ex; } } /// <summary> /// 类赋值(两个类属性相似赋值) /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="E"></typeparam> /// <param name="pTargetObjSrc">目标类</param> /// <param name="pTargetObjDest">源类</param> public static void EntityToEntity<T, E>(T pTargetObjSrc, E pTargetObjDest) { try { foreach (var mItem in typeof(T).GetProperties()) { mItem.SetValue(pTargetObjDest, mItem.GetValue(pTargetObjSrc, new object[] { }), null); } } catch (NullReferenceException NullEx) { throw NullEx; } catch (Exception Ex) { throw Ex; } } #region 类 /// <summary> /// 表单数据项 /// </summary> public class FormItemModel { public FormitemTypeEnum formItemType { get; set; } = FormitemTypeEnum.文本; /// <summary> /// 表单键,request["key"] /// </summary> public string Key { set; get; } /// <summary> /// 表单值,上传文件时忽略,request["key"].value /// 格式:application/octet-stream /// </summary> public string Value { set; get; } public byte[] pic_bytes { get; set; } /// <summary> /// 是否是文件 /// </summary> public bool IsFile { get { if (FileContent == null || FileContent.Length == 0) return false; if (FileContent != null && FileContent.Length > 0 && string.IsNullOrWhiteSpace(FileName)) throw new Exception("上传文件时 FileName 属性值不能为空"); return true; } } /// <summary> /// 上传的文件名 /// </summary> public string FileName { set; get; } /// <summary> /// 上传的文件内容 /// </summary> public Stream FileContent { set; get; } } /// <summary> /// Form上传类型 /// </summary> public enum FormitemTypeEnum { 文本 = 0, 文件 = 1, 图片 = 2 } /// <summary> /// (专用)微讯同步上传返回信息 /// </summary> public class ZY_MicronewsResult { public string response { get; set; } public ModelError error { get; set; } public class ModelError { /// <summary> /// 错误码 /// </summary> public int code { get; set; } /// <summary> /// 错误描述 /// </summary> public string description { get; set; } } } #endregion public static class IO { /// 将 Stream 转成 byte[] public static byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } /// 将 byte[] 转成 Stream public static Stream BytesToStream(byte[] bytes) { Stream stream = new MemoryStream(bytes); return stream; } } /// <summary> /// 汉字转换 /// </summary> public class ChineseConvert { #region 汉字转拼方法1 /// <summary>汉字转拼音缩写</summary> /// <param name="str">要转换的汉字字符串</param> /// <returns>拼音缩写</returns> public static string GetSpellString(string str) { if (IsEnglishCharacter(str)) return str; string tempStr = ""; foreach (char c in str) { if ((int)c >= 33 && (int)c <= 126) {//字母和符号原样保留 tempStr += c.ToString(); } else {//累加拼音声母 tempStr += GetSpellChar(c.ToString()); } } return tempStr; } /// <summary> /// 判断是否字母 /// </summary> /// <param name="str"></param> /// <returns></returns> private static bool IsEnglishCharacter(String str) { CharEnumerator ce = str.GetEnumerator(); while (ce.MoveNext()) { char c = ce.Current; if ((c <= 0x007A && c >= 0x0061) == false && (c <= 0x005A && c >= 0x0041) == false) return false; } return true; } /// <summary> /// 判断是否有汉字 /// </summary> /// <param name="testString"></param> /// <returns></returns> private static bool HaveChineseCode(string testString) { if (Regex.IsMatch(testString, @"[u4e00-u9fa5]+")) { return true; } else { return false; } } /// <summary> /// 取单个字符的拼音声母 /// </summary> /// <param name="c">要转换的单个汉字</param> /// <returns>拼音声母</returns> public static string GetSpellChar(string c) { byte[] array = new byte[2]; array = System.Text.Encoding.Default.GetBytes(c); int i = (short)(array[0] - '