/// <summary> /// 字符串编码帮助类 /// </summary> public class EncodingHelper { /// <summary> /// 字符串编码转换 /// </summary> /// <param name="srcEncoding">原编码</param> /// <param name="dstEncoding">目标编码</param> /// <param name="srcStr">原字符串</param> /// <returns>字符串</returns> internal static string TransferEncoding(Encoding srcEncoding, Encoding dstEncoding, string srcStr) { byte[] srcBytes = srcEncoding.GetBytes(srcStr); byte[] bytes = Encoding.Convert(srcEncoding, dstEncoding, srcBytes); return dstEncoding.GetString(bytes); } /// <summary> /// Base64转码 /// </summary> /// <param name="srcStr">原字符串</param> /// <returns>字符串</returns> internal static string ToBase64(string srcStr) { byte[] bytes = Encoding.Default.GetBytes(srcStr); return Convert.ToBase64String(bytes); } /// <summary> /// Base64字符串解码 /// </summary> /// <param name="srcStr">Base64 字符串</param> /// <returns>字符串</returns> internal static string ToUnBase64(string srcStr) { byte[] bytes = Convert.FromBase64String(srcStr); return Encoding.Default.GetString(bytes);//Convert.ToBase64String(bytes); } /// <summary> /// 正则匹配并返回网页编码。 /// </summary> /// <param name="html"></param> /// <returns></returns> internal static Encoding GetHtmlCharSet(string html) { Encoding encoding; string webCharSet = MatchHelper.MatchScalar(html, "charset=[\"]*(\\S+)\""); if (webCharSet.Trim() == "") { webCharSet = MatchHelper.MatchScalar(html, "encoding=\"(\\S+)\""); } switch (webCharSet.ToLower()) { case "gbk": case "gb2312": encoding = Encoding.Default; break; case "utf8": case "utf-8": encoding = Encoding.UTF8; break; case "unicode": encoding = Encoding.Unicode; break; case "ascii": encoding = Encoding.ASCII; break; default: encoding = Encoding.Default; break; } return encoding; } /// <summary> /// 将字节数组转为字符串 /// </summary> /// <param name="b">字节数组</param> /// <param name="Encoding">编码,默认为Default</param> /// <returns></returns> internal static string ByteToString(byte[] b, Encoding Encoding) { if (Encoding == null) { Encoding = Encoding.Default; } string result = Encoding.GetString(b); return result; } /// <summary> /// 将字符串转为字节数组 /// </summary> /// <param name="str">字符串</param> /// <param name="Encoding">编码,默认为Default</param> /// <returns></returns> internal static byte[] StringToByte(string str, Encoding Encoding) { if (Encoding == null) { Encoding = Encoding.Default; } byte[] b = Encoding.GetBytes(str); return b; } }
11
2015
07
C#字符串编码帮助类
发布:郑德才博客 | 分类:学习之路 | 评论:0 | 浏览:
相关文章:
C#、Asp.Net 对比两个实体信息前后是否有所改变(结构相同和不相同) (2016-9-2 20:24:29)
C#、Asp.Net 将一个实体对象转换为另一个实体对象(结构可以不一样) (2016-9-2 19:14:5)
【C#、Asp.Net 工具类大全】图片通用操作类 (2015-12-23 13:27:30)
【C#、Asp.Net 工具类大全】Request请求工具类 (2015-12-23 13:15:56)
【C#、Asp.Net 工具类大全】弹出提示操作类 (2015-12-23 13:6:1)
【C#、Asp.Net 工具类大全】正则匹配工具类 (2015-7-26 9:36:56)
【C#、Asp.Net 工具类大全】Js常用操作类 (2015-7-15 14:23:33)
【C#、Asp.Net 工具类大全】Html常用帮助类 (2015-7-11 23:42:53)
【C#、Asp.Net 工具类大全】压缩文本、字节或者文件的压缩辅助类 (2015-7-11 23:23:49)
【C#、Asp.Net-工具类大全】FTP文件操作工具类 (2015-7-6 13:47:20)
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。