c#编码转换问题

来源:百度知道 编辑:UC知道 时间:2024/05/22 14:37:03
我现在想把一个字符串转换成utf-8格式的怎么做?

比如实现Utf-8和GB2312的转换:

string gb2312info = "你好!";
string utfinfo = string.Empty;
Encoding utf8 = Encoding.UTF8;
Encoding gb2312 = Encoding.GetEncoding("gb2312");

// Convert the string into a byte[].
byte[] unicodeBytes = gb2312 .GetBytes(gb2312info );
// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(gb2312,utf8, 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[] asciiChars = new char[utf8 .GetCharCount(asciiBytes, 0, asciiBytes.Length)];
utf8 .GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
utfinfo = new string(asciiChars);