如何在c#中将标签文本转换为UTF-8

时间:2015-01-27 12:31:38

标签: c# utf-8 character-encoding

我试图将标签的文本转换为c#中的utf-8,我该怎么办?

            lblName.Text = e.displayName;

3 个答案:

答案 0 :(得分:2)

您应该查看那里的MSDN示例中提到的解决方案: https://msdn.microsoft.com/en-us/library/system.text.utf8encoding(v=vs.90).aspx

using System;
using System.Text;

class UTF8EncodingExample {
public static void Main() {
    // Create a UTF-8 encoding.
    UTF8Encoding utf8 = new UTF8Encoding();

    // A Unicode string with two characters outside an 8-bit code range.
    String unicodeString =
        "This unicode string contains two characters " +
        "with codes outside an 8-bit code range, " +
        "Pi (\u03a0) and Sigma (\u03a3).";
    Console.WriteLine("Original string:");
    Console.WriteLine(unicodeString);

    // Encode the string.
    Byte[] encodedBytes = utf8.GetBytes(unicodeString);
    Console.WriteLine();
    Console.WriteLine("Encoded bytes:");
    foreach (Byte b in encodedBytes) {
        Console.Write("[{0}]", b);
    }
    Console.WriteLine();

    // Decode bytes back to string. 
    // Notice Pi and Sigma characters are still present.
    String decodedString = utf8.GetString(encodedBytes);
    Console.WriteLine();
    Console.WriteLine("Decoded bytes:");
    Console.WriteLine(decodedString);
}}

答案 1 :(得分:1)

您无法更改字符串的编码。在.NET中,字符串使用UTF-16进行内部编码。只有当字符串转换为字节序列或从字节序列转换字符串时才能影响编码(例如,写入/读取文件)。

答案 2 :(得分:0)

在C#中,String使用UTF-16。因此,你可能没有这个问题。

我认为您的html字符集存在问题。

要将页面字符集设置为" UTF-8",请在页眉上设置以下内容

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">