//将汉字转换成GB2312编码 private byte[] StringToBytes(string TheString) { Encoding fromEcoding = Encoding.GetEncoding("UTF-8");//返回utf-8的编码 Encoding toEcoding = Encoding.GetEncoding("gb2312"); byte[] fromBytes = fromEcoding.GetBytes(TheString); byte[] tobytes = Encoding.Convert(fromEcoding, toEcoding, fromBytes);//将字节数组从一种编码转换为另一种编码 return tobytes; } //将GB2312编码转换成汉字 private string BytesToString(byte[] bytes) { string myString; Encoding fromEcoding = Encoding.GetEncoding("gb2312"); Encoding toEcoding = Encoding.GetEncoding("UTF-8"); byte[] toBytes = Encoding.Convert(fromEcoding, toEcoding, bytes); myString = toEcoding.GetString(toBytes);//将字节数组解码成字符串 return myString; }
注意,如果报错
“'gb2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. Arg_ParamName_Name”
在nuget中安装System.Text.CodePages,在需要转码的地方插入如下代码:
//将汉字转换成GB2312编码 private static byte[] StringToBytes(string TheString) {
//插入此代码 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Encoding fromEcoding = Encoding.GetEncoding("UTF-8");//返回utf-8的编码 Encoding toEcoding = Encoding.GetEncoding("gb2312"); byte[] fromBytes = fromEcoding.GetBytes(TheString); byte[] tobytes = Encoding.Convert(fromEcoding, toEcoding, fromBytes);//将字节数组从一种编码转换为另一种编码 return tobytes; }
翻译
搜索
复制
:“'gb2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. Arg_ParamName_Name” 标签:编码,Encoding,gb2312,汉字,fromEcoding,byte,toEcoding From: https://www.cnblogs.com/zzgxl/p/17405950.html