如何将字符串转换为UTF8?

时间:2012-01-03 04:01:35

标签: c# .net character-encoding

我有一个包含一些unicode的字符串,如何将其转换为UTF-8编码?

4 个答案:

答案 0 :(得分:23)

此代码段生成一个字节数组,其字符串以UTF-8编码:

UTF8Encoding utf8 = new UTF8Encoding();
string unicodeString = "Quick brown fox";
byte[] encodedBytes = utf8.GetBytes(unicodeString);

答案 1 :(得分:3)

尝试此功能,这应该是开箱即用的,您可能需要修复命名约定。

private string UnicodeToUTF8(string strFrom)
{
byte[] bytSrc;
byte[] bytDestination;
string strTo = String.Empty;

bytSrc = Encoding.Unicode.GetBytes(strFrom);
bytDestination = Encoding.Convert(Encoding.Unicode, Encoding.ASCII, bytSrc);
strTo = Encoding.ASCII.GetString(bytDestination);

return strTo;
}

答案 2 :(得分:1)

尝试此代码

 string unicodeString = "Quick brown fox";
 var bytes = new List<byte>(unicodeString);
        foreach (var c in unicodeString)
            bytes.Add((byte)c);
        var retValue = Encoding.UTF8.GetString(bytes.ToArray());

答案 3 :(得分:1)

这应该是最小代码:

byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);