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> /// 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转换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 = @"^<img\s+[^>]*>"; Regex r = new Regex(@"<img\s+[^>]*\s*src\s*=\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\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""‘]?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""‘<>]*)[^<>]*?/?[\s\t\r\n]*>"); 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] - ‘\0‘) * 256 + ((short)(array[1] - ‘\0‘)); if (i < 0xB0A1) return "*"; if (i < 0xB0C5) return "a"; if (i < 0xB2C1) return "b"; if (i < 0xB4EE) return "c"; if (i < 0xB6EA) return "d"; if (i < 0xB7A2) return "e"; if (i < 0xB8C1) return "f"; if (i < 0xB9FE) return "g"; if (i < 0xBBF7) return "h"; if (i < 0xBFA6) return "j"; if (i < 0xC0AC) return "k"; if (i < 0xC2E8) return "l"; if (i < 0xC4C3) return "m"; if (i < 0xC5B6) return "n"; if (i < 0xC5BE) return "o"; if (i < 0xC6DA) return "p"; if (i < 0xC8BB) return "q"; if (i < 0xC8F6) return "r"; if (i < 0xCBFA) return "s"; if (i < 0xCDDA) return "t"; if (i < 0xCEF4) return "w"; if (i < 0xD1B9) return "x"; if (i < 0xD4D1) return "y"; if (i < 0xD7FA) return "z"; return "*"; } #endregion #region 汉字转拼方法2 private static Hashtable _Phrase; /// <summary> /// 设置或获取包含列外词组读音的键/值对的组合。 /// </summary> public static Hashtable Phrase { get { if (_Phrase == null) { _Phrase = new Hashtable(); _Phrase.Add("圳", "Zhen"); _Phrase.Add("什么", "ShenMe"); _Phrase.Add("晖", "Hui"); _Phrase.Add("孑", "Jie"); } return _Phrase; } set { _Phrase = value; } } #region 定义编码 private static int[] pyvalue = new int[] { -20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032, -20026, -20002, -19990, -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728, -19725, -19715, -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261, -19249, -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961, -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, -18490, -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, -17997, -17988, -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, -17701, -17697, -17692, -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, -16970, -16942, -16915, -16733, -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, -16433, -16429, -16427, -16423, -16419, -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, -16180, -16171, -16169, -16158, -16155, -15959, -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, -15681, -15667, -15661, -15659, -15652, -15640, -15631, -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180, -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941, -14937, -14933, -14930, -14929, -14928, -14926, -14922, -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857, -14678, -14674, -14670, -14668, -14663, -14654, -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353, -14345, -14170, -14159, -14151, -14149, -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094, -14092, -14090, -14087, -14083, -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831, -13658, -13611, -13601, -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329, -13326, -13318, -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860, -12858, -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300, -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, -11358, -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, -11018, -11014, -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, -10322, -10315, -10309, -10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254 }; private static string[] pystr = new string[] { "a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian", "biao", "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan" , "chang", "chao", "che", "chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong" , "cou", "cu", "cuan", "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", "die", "ding", "diu", "dong", "dou", "du", "duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", "fei", "fen", "feng", "fo", "fou", "fu", "ga" , "gai", "gan", "gang", "gao", "ge", "gei", "gen", "geng", "gong", "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang", "hao", "he", "hei", "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian", "jiang", "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", "ken", "keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", "lao", "le", "lei", "leng", "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", "lv", "luan", "lue", "lun", "luo", "ma", "mai", "man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai", "nan", "nang", "nao", "ne", "nei", "nen", "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan", "nue", "nuo", "o", "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", "rang", "rao", "re", "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", "sang", "sao", "se", "sen", "seng", "sha", "shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", "shua", "shuai", "shuan", "shuang", "shui", "shun", "shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao", "tie", "ting", "tong", "tou", "tu", "tuan", "tui", "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi", "yin", "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", "zeng", "zha", "zhai" , "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", "zhuang", "zhui", "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo" }; #endregion #region 获取汉字拼音 /// <summary> /// 获取汉字拼音 /// </summary> /// <param name="chsstr">汉字字符串</param> /// <returns>拼音</returns> public static string GetSpellByChinese(string _chineseString) { string strRet = string.Empty; // 例外词组 foreach (DictionaryEntry de in Phrase) { _chineseString = _chineseString.Replace(de.Key.ToString(), de.Value.ToString()); } char[] ArrChar = _chineseString.ToCharArray(); foreach (char c in ArrChar) { strRet += GetSingleSpellByChinese(c.ToString()); } return strRet; } #endregion #region 获取汉字拼音首字母 /// <summary> /// 获取汉字拼音首字母 /// </summary> /// <param name="chsstr">指定汉字</param> /// <returns>拼音首字母</returns> public static string GetHeadSpellByChinese(string _chineseString) { string strRet = string.Empty; char[] ArrChar = _chineseString.ToCharArray(); foreach (char c in ArrChar) { strRet += GetHeadSingleSpellByChinese(c.ToString()); } return strRet; } #endregion #region 获取单个汉字拼音 /// <summary> /// 获取单个汉字拼音 /// </summary> /// <param name="SingleChs">单个汉字</param> /// <returns>拼音</returns> public static string GetSingleSpellByChinese(string _singleChineseString) { byte[] array = Encoding.Default.GetBytes(_singleChineseString); int iAsc; string strRtn = string.Empty; try { iAsc = (short)(array[0]) * 256 + (short)(array[1]) - 65536; } catch { iAsc = 1; } if (iAsc > 0 && iAsc < 160) return _singleChineseString; for (int i = (pyvalue.Length - 1); i >= 0; i--) { if (pyvalue[i] <= iAsc) { strRtn = pystr[i]; break; } } //将首字母转为大写 if (strRtn.Length > 1) { strRtn = strRtn.Substring(0, 1).ToUpper() + strRtn.Substring(1); } return strRtn; } #endregion #region 获取单个汉字的首字母 /// <summary> /// 获取单个汉字的首字母 /// </summary> /// <returns></returns> public static string GetHeadSingleSpellByChinese(string _singleChineseString) { // 例外词组 foreach (DictionaryEntry de in Phrase) { _singleChineseString = _singleChineseString.Replace(de.Key.ToString(), de.Value.ToString()); } string text = ""; try { text = GetSingleSpellByChinese(_singleChineseString).Substring(0, 1); } catch { } return text; } #endregion #region 获取汉字拼音(第一个汉字只有首字母) /// <summary> /// 获取汉字拼音(第一个汉字只有首字母) /// </summary> /// <param name="_chineseString"></param> /// <returns></returns> public static string GetAbSpellByChinese(string _chineseString) { string strRet = string.Empty; // 例外词组 foreach (DictionaryEntry de in Phrase) { _chineseString = _chineseString.Replace(de.Key.ToString(), de.Value.ToString()); } char[] ArrChar = _chineseString.ToCharArray(); for (int i = 0; i < ArrChar.Length; i++) { if (i == 0) { strRet += GetHeadSingleSpellByChinese(ArrChar[i].ToString()); } else { strRet += GetSingleSpellByChinese(ArrChar[i].ToString()); } } return strRet; } #endregion /// <summary> /// 获取5种汉字转拼音 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetAllSpellByChinese(string str) { string str_temp = ""; str_temp = GetSpellByChinese(str.Trim()); str_temp += "," + GetHeadSpellByChinese(str.Trim()); str_temp += "," + GetSingleSpellByChinese(str.Trim()); str_temp += "," + GetHeadSingleSpellByChinese(str.Trim()); str_temp += "," + GetAbSpellByChinese(str.Trim()); return str_temp; } /// <summary> /// 获取5种汉字转拼音 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetAllSpellByChinese(string str, string fg) { string str_temp = ""; str_temp = GetSpellByChinese(str.Trim()); str_temp += fg + GetHeadSpellByChinese(str.Trim()); str_temp += fg + GetSingleSpellByChinese(str.Trim()); str_temp += fg + GetHeadSingleSpellByChinese(str.Trim()); str_temp += fg + GetAbSpellByChinese(str.Trim()); return str_temp; } #endregion } } }
原文地址:https://www.cnblogs.com/OleRookie/p/8390752.html
时间: 2024-11-09 01:49:41