GooglePrettify

2018年12月26日 星期三

Encoding of C# (CLR)

A string in C# is always UTF-16

If request from website is using UTF-8, you will always need to do the conversion from UTF-16 to UTF-8 as below:
public static string Utf16ToUtf8(string utf16String)
{
    // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
    byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
    byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);

    // Return UTF8 bytes as ANSI string
    return Encoding.Default.GetString(utf8Bytes);
}

沒有留言:

張貼留言