有一段把unicode转换为GB2312的代码,不知可否借鉴。 string unicodeString = "字符编码有多种方式,其中常用的有GB2312和UTF-8等等(\u03a0)"; // Create two different encodings. Encoding gb = Encoding.GetEncoding( "gb2312" ); Encoding unicode = Encoding.Unicode; // Convert the string into a byte[]. byte[] unicodeBytes = unicode.GetBytes(unicodeString); // Perform the conversion from one encoding to the other. byte[] gbBytes = Encoding.Convert(unicode, gb, unicodeBytes);
// Convert the new byte[] into a char[] and then into a string. // This is a slightly different approach to converting to illustrate // the use of GetCharCount/GetChars. char[] gbChars = new char[gb.GetCharCount(gbBytes, 0, gbBytes.Length)]; gb.GetChars(gbBytes, 0, gbBytes.Length, gbChars, 0); string gbString = new string(gbChars); // Display the strings created before and after the conversion. Console.WriteLine("Original string: {0}", unicodeString); Console.WriteLine("Ascii converted string: {0}", gbString);
如果是byte[],并且是以utf-8类型写入得,那么Encoding.UTF8.GetString(...);
如果是string,Encoding.UTF8.GetBytes(...);
Encoding gb = Encoding.GetEncoding( "gb2312" );
Encoding unicode = Encoding.Unicode; // Convert the string into a byte[].
byte[] unicodeBytes = unicode.GetBytes(unicodeString); // Perform the conversion from one encoding to the other.
byte[] gbBytes = Encoding.Convert(unicode, gb, unicodeBytes);
// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.
char[] gbChars = new char[gb.GetCharCount(gbBytes, 0, gbBytes.Length)];
gb.GetChars(gbBytes, 0, gbBytes.Length, gbChars, 0);
string gbString = new string(gbChars); // Display the strings created before and after the conversion.
Console.WriteLine("Original string: {0}", unicodeString);
Console.WriteLine("Ascii converted string: {0}", gbString);
用它
用它
用它
用它
用它
用它
用它
还有 它:System.Text.Encoding.UTF8
一般的来说,输出都使用输出流来实现的。设置StreamWriter的Encoding即可。