通过


UTF8Encoding 类

定义

表示 Unicode 字符的 UTF-8 编码。

public ref class UTF8Encoding : System::Text::Encoding
public class UTF8Encoding : System.Text.Encoding
[System.Serializable]
public class UTF8Encoding : System.Text.Encoding
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class UTF8Encoding : System.Text.Encoding
type UTF8Encoding = class
    inherit Encoding
[<System.Serializable>]
type UTF8Encoding = class
    inherit Encoding
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type UTF8Encoding = class
    inherit Encoding
Public Class UTF8Encoding
Inherits Encoding
继承
UTF8Encoding
属性

示例

以下示例使用对象 UTF8Encoding 对 Unicode 字符的字符串进行编码,并将其存储在字节数组中。 Unicode 字符串包括两个字符(Pi(U+03A0)和 Sigma(U+03A3),这些字符超出了 ASCII 字符范围。 将编码的字节数组解码回字符串时,Pi 和 Sigma 字符仍存在。

using System;
using System.Text;

class Example
{
    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 has 2 characters outside the " +
            "ASCII range:\n" +
            "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:");
        for (int ctr = 0; ctr < encodedBytes.Length; ctr++) {
            Console.Write("{0:X2} ", encodedBytes[ctr]);
            if ((ctr + 1) %  25 == 0)
               Console.WriteLine();
        }
        Console.WriteLine();
        
        // Decode bytes back to string.
        String decodedString = utf8.GetString(encodedBytes);
        Console.WriteLine();
        Console.WriteLine("Decoded bytes:");
        Console.WriteLine(decodedString);
    }
}
// The example displays the following output:
//    Original string:
//    This Unicode string has 2 characters outside the ASCII range:
//    Pi (π), and Sigma (Σ).
//
//    Encoded bytes:
//    54 68 69 73 20 55 6E 69 63 6F 64 65 20 73 74 72 69 6E 67 20 68 61 73 20 32
//    20 63 68 61 72 61 63 74 65 72 73 20 6F 75 74 73 69 64 65 20 74 68 65 20 41
//    53 43 49 49 20 72 61 6E 67 65 3A 20 0D 0A 50 69 20 28 CE A0 29 2C 20 61 6E
//    64 20 53 69 67 6D 61 20 28 CE A3 29 2E
//
//    Decoded bytes:
//    This Unicode string has 2 characters outside the ASCII range:
//    Pi (π), and Sigma (Σ).
Imports System.Text

Class Example
    Public Shared Sub Main()
        ' Create a UTF-8 encoding.
        Dim utf8 As New UTF8Encoding()
        
        ' A Unicode string with two characters outside an 8-bit code range.
        Dim unicodeString As String = _
            "This Unicode string has 2 characters outside the " &
            "ASCII range: " & vbCrLf &
            "Pi (" & ChrW(&h03A0) & "), and Sigma (" & ChrW(&h03A3) & ")."
        Console.WriteLine("Original string:")
        Console.WriteLine(unicodeString)
        
        ' Encode the string.
        Dim encodedBytes As Byte() = utf8.GetBytes(unicodeString)
        Console.WriteLine()
        Console.WriteLine("Encoded bytes:")
        For ctr As Integer = 0 To encodedBytes.Length - 1
            Console.Write("{0:X2} ", encodedBytes(ctr))
            If (ctr + 1) Mod 25 = 0 Then Console.WriteLine
        Next
        Console.WriteLine()
        
        ' Decode bytes back to string.
        Dim decodedString As String = utf8.GetString(encodedBytes)
        Console.WriteLine()
        Console.WriteLine("Decoded bytes:")
        Console.WriteLine(decodedString)
    End Sub
End Class
' The example displays the following output:
'    Original string:
'    This Unicode string has 2 characters outside the ASCII range:
'    Pi (π), and Sigma (Σ).
'
'    Encoded bytes:
'    54 68 69 73 20 55 6E 69 63 6F 64 65 20 73 74 72 69 6E 67 20 68 61 73 20 32
'    20 63 68 61 72 61 63 74 65 72 73 20 6F 75 74 73 69 64 65 20 74 68 65 20 41
'    53 43 49 49 20 72 61 6E 67 65 3A 20 0D 0A 50 69 20 28 CE A0 29 2C 20 61 6E
'    64 20 53 69 67 6D 61 20 28 CE A3 29 2E
'
'    Decoded bytes:
'    This Unicode string has 2 characters outside the ASCII range:
'    Pi (π), and Sigma (Σ).

以下示例使用与前面的示例相同的字符串,只不过它将编码的字节写入文件,并使用字节顺序标记(BOM)为字节流添加前缀。 然后,它以两种不同的方式读取文件:使用 StreamReader 对象作为文本文件;作为二进制文件。 正如预期的那样,新读取的字符串都不包括 BOM。

using System;
using System.IO;
using System.Text;

public class Example
{
   public static void Main()
   {
        // Create a UTF-8 encoding that supports a BOM.
        Encoding utf8 = new UTF8Encoding(true);

        // A Unicode string with two characters outside an 8-bit code range.
        String unicodeString =
            "This Unicode string has 2 characters outside the " +
            "ASCII range:\n" +
            "Pi (\u03A0)), and Sigma (\u03A3).";
        Console.WriteLine("Original string:");
        Console.WriteLine(unicodeString);
        Console.WriteLine();

        // Encode the string.
        Byte[] encodedBytes = utf8.GetBytes(unicodeString);
        Console.WriteLine("The encoded string has {0} bytes.",
                          encodedBytes.Length);
        Console.WriteLine();

        // Write the bytes to a file with a BOM.
        var fs = new FileStream(@".\UTF8Encoding.txt", FileMode.Create);
        Byte[] bom = utf8.GetPreamble();
        fs.Write(bom, 0, bom.Length);
        fs.Write(encodedBytes, 0, encodedBytes.Length);
        Console.WriteLine("Wrote {0} bytes to the file.", fs.Length);
        fs.Close();
        Console.WriteLine();

        // Open the file using StreamReader.
        var sr = new StreamReader(@".\UTF8Encoding.txt");
        String newString = sr.ReadToEnd();
        sr.Close();
        Console.WriteLine("String read using StreamReader:");
        Console.WriteLine(newString);
        Console.WriteLine();

        // Open the file as a binary file and decode the bytes back to a string.
        fs = new FileStream(@".\UTF8Encoding.txt", FileMode.Open);
        Byte[] bytes = new Byte[fs.Length];
        fs.Read(bytes, 0, (int)fs.Length);
        fs.Close();

        String decodedString = utf8.GetString(bytes);
        Console.WriteLine("Decoded bytes:");
        Console.WriteLine(decodedString);
   }
}
// The example displays the following output:
//    Original string:
//    This Unicode string has 2 characters outside the ASCII range:
//    Pi (π), and Sigma (Σ).
//
//    The encoded string has 88 bytes.
//
//    Wrote 91 bytes to the file.
//
//    String read using StreamReader:
//    This Unicode string has 2 characters outside the ASCII range:
//    Pi (π), and Sigma (Σ).
//
//    Decoded bytes:
//    This Unicode string has 2 characters outside the ASCII range:
//    Pi (π), and Sigma (Σ).
Imports System.IO
Imports System.Text

Class Example
    Public Shared Sub Main()
        ' Create a UTF-8 encoding that supports a BOM.
        Dim utf8 As New UTF8Encoding(True)
        
        ' A Unicode string with two characters outside an 8-bit code range.
        Dim unicodeString As String = _
            "This Unicode string has 2 characters outside the " &
            "ASCII range: " & vbCrLf &
            "Pi (" & ChrW(&h03A0) & "), and Sigma (" & ChrW(&h03A3) & ")."
        Console.WriteLine("Original string:")
        Console.WriteLine(unicodeString)
        Console.WriteLine()
        
        ' Encode the string.
        Dim encodedBytes As Byte() = utf8.GetBytes(unicodeString)
        Console.WriteLine("The encoded string has {0} bytes.",
                          encodedBytes.Length)
        Console.WriteLine()
        
        ' Write the bytes to a file with a BOM.
        Dim fs As New FileStream(".\UTF8Encoding.txt", FileMode.Create)
        Dim bom() As Byte = utf8.GetPreamble()
        fs.Write(bom, 0, bom.Length)
        fs.Write(encodedBytes, 0, encodedBytes.Length)
        Console.WriteLine("Wrote {0} bytes to the file.", fs.Length)
        fs.Close()
        Console.WriteLine()
        
        ' Open the file using StreamReader.
        Dim sr As New StreamReader(".\UTF8Encoding.txt")
        Dim newString As String = sr.ReadToEnd()
        sr.Close()
        Console.WriteLine("String read using StreamReader:")
        Console.WriteLine(newString)
        Console.WriteLine()
        
        ' Open the file as a binary file and decode the bytes back to a string.
        fs = new FileStream(".\UTF8Encoding.txt", FileMode.Open)
        Dim bytes(fs.Length - 1) As Byte
        fs.Read(bytes, 0, fs.Length)
        fs.Close()

        Dim decodedString As String = utf8.GetString(bytes)
        Console.WriteLine("Decoded bytes:")
        Console.WriteLine(decodedString)
    End Sub
End Class
' The example displays the following output:
'    Original string:
'    This Unicode string has 2 characters outside the ASCII range:
'    Pi (π), and Sigma (Σ).
'
'    The encoded string has 88 bytes.
'
'    Wrote 91 bytes to the file.
'
'    String read using StreamReader:
'    This Unicode string has 2 characters outside the ASCII range:
'    Pi (π), and Sigma (Σ).
'
'    Decoded bytes:
'    This Unicode string has 2 characters outside the ASCII range:
'    Pi (π), and Sigma (Σ).

注解

编码是将一组 Unicode 字符转换为字节序列的过程。 解码是将编码字节序列转换为一组 Unicode 字符的过程。

UTF-8 是一种 Unicode 编码,将每个代码点表示为一到四个字节的序列。 与 UTF-16 和 UTF-32 编码不同,UTF-8 编码不需要“endianness”:无论处理器是 big-endian 还是 little-endian,编码方案都是相同的。 UTF8Encoding 对应于 Windows 代码页 65001。 有关 UTF 和支持的其他编码 System.Text的详细信息,请参阅 .NET Framework 中的字符编码

可以通过多种方式实例化 UTF8Encoding 对象,具体取决于是否要它提供字节顺序标记(BOM),以及是否要启用错误检测。 下表列出了返回对象的UTF8Encoding构造函数和Encoding属性。

成员 BOM 错误检测
Encoding.UTF8 是的 否(替换回退)
UTF8Encoding.UTF8Encoding() 否(替换回退)
UTF8Encoding.UTF8Encoding(Boolean) 可配置 否(替换回退)
UTF8Encoding.UTF8Encoding(Boolean, Boolean) 可配置 可配置

该方法 GetByteCount 确定对一组 Unicode 字符进行编码的字节数,该方法 GetBytes 执行实际编码。

同样,该方法 GetCharCount 确定对字节序列进行解码的字符数,以及 GetChars 执行 GetString 实际解码的方法。

对于能够保存状态信息的编码器或解码器,当编码或解码跨越多个块的数据(如编码为 100,000 个字符段的字符串)时,请分别使用 GetEncoderGetDecoder 属性。

(可选)对象 UTF8Encoding 提供字节顺序标记(BOM),该标记是一个字节数组,可以作为字节流开头的前缀,该字节由编码过程产生。 如果 UTF-8 编码字节流以字节顺序标记(BOM)开头,则它有助于解码器确定字节顺序和转换格式或 UTF。 但是,请注意,Unicode 标准既不需要也不建议 UTF-8 编码流中的 BOM。 有关字节顺序和字节顺序标记的详细信息,请参阅 Unicode 主页上的 Unicode 标准版。

如果编码器配置为提供 BOM,则可以通过调用 GetPreamble 该方法来检索它;否则,该方法将返回一个空数组。 请注意,即使为 BOM 支持配置了对象 UTF8Encoding ,也必须在编码字节流的开头包含 BOM;类的 UTF8Encoding 编码方法不会自动执行此操作。

注意

若要启用错误检测并使类实例更安全,应调用 UTF8Encoding(Boolean, Boolean) 构造函数并将参数设置为 throwOnInvalidBytestrue。 启用错误检测后,检测无效字符或字节序列的方法将引发 ArgumentException 异常。 如果没有错误检测,不会引发异常,并且通常忽略无效序列。

注释

如果使用不同的 .NET Framework 版本序列化和反序列化对象,则不会保留 UTF-8 编码对象的状态。

构造函数

名称 说明
UTF8Encoding()

初始化 UTF8Encoding 类的新实例。

UTF8Encoding(Boolean, Boolean)

初始化 UTF8Encoding 类的新实例。 参数指定是否提供 Unicode 字节顺序标记,以及是否在检测到无效编码时引发异常。

UTF8Encoding(Boolean)

初始化 UTF8Encoding 类的新实例。 参数指定是否提供 Unicode 字节顺序标记。

属性

名称 说明
BodyName

在派生类中重写时,获取可用于邮件代理正文标记的当前编码的名称。

(继承自 Encoding)
CodePage

在派生类中重写时,获取当前 Encoding代码页标识符。

(继承自 Encoding)
DecoderFallback

获取或设置 DecoderFallback 当前 Encoding 对象的对象。

(继承自 Encoding)
EncoderFallback

获取或设置 EncoderFallback 当前 Encoding 对象的对象。

(继承自 Encoding)
EncodingName

在派生类中重写时,获取当前编码的人类可读说明。

(继承自 Encoding)
HeaderName

在派生类中重写时,获取可用于邮件代理标头标记的当前编码的名称。

(继承自 Encoding)
IsBrowserDisplay

在派生类中重写时,获取一个值,该值指示浏览器客户端是否可以使用当前编码来显示内容。

(继承自 Encoding)
IsBrowserSave

在派生类中重写时,获取一个值,该值指示浏览器客户端是否可以使用当前编码来保存内容。

(继承自 Encoding)
IsMailNewsDisplay

在派生类中重写时,获取一个值,该值指示邮件和新闻客户端是否可以使用当前编码来显示内容。

(继承自 Encoding)
IsMailNewsSave

在派生类中重写时,获取一个值,该值指示邮件和新闻客户端是否可以使用当前编码来保存内容。

(继承自 Encoding)
IsReadOnly

在派生类中重写时,获取一个值,该值指示当前编码是否为只读。

(继承自 Encoding)
IsSingleByte

在派生类中重写时,获取一个值,该值指示当前编码是否使用单字节码位。

(继承自 Encoding)
Preamble

如果此对象配置为提供一个,则获取以 UTF-8 格式编码的 Unicode 字节顺序标记。

Preamble

在派生类中重写时,返回包含指定所用编码的字节序列的范围。

(继承自 Encoding)
WebName

在派生类中重写时,获取为当前编码向 Internet 分配号码颁发机构(IANA)注册的名称。

(继承自 Encoding)
WindowsCodePage

在派生类中重写时,获取与当前编码最接近的 Windows 操作系统代码页。

(继承自 Encoding)

方法

名称 说明
Clone()

在派生类中重写时,创建当前 Encoding 对象的浅表副本。

(继承自 Encoding)
Equals(Object)

确定指定的对象是否等于当前 UTF8Encoding 对象。

GetByteCount(Char[], Int32, Int32)

计算通过对指定字符数组中的一组字符进行编码而生成的字节数。

GetByteCount(Char[])

在派生类中重写时,计算通过编码指定字符数组中的所有字符生成的字节数。

(继承自 Encoding)
GetByteCount(Char*, Int32)

计算从指定字符指针开始对一组字符进行编码生成的字节数。

GetByteCount(ReadOnlySpan<Char>)

计算通过编码指定字符范围生成的字节数。

GetByteCount(ReadOnlySpan<Char>)

在派生类中重写时,计算通过对指定字符范围中的字符进行编码生成的字节数。

(继承自 Encoding)
GetByteCount(String, Int32, Int32)

在派生类中重写时,计算通过对指定字符串中的一组字符进行编码生成的字节数。

(继承自 Encoding)
GetByteCount(String)

计算通过对指定 String字符进行编码生成的字节数。

GetBytes(Char[], Int32, Int32, Byte[], Int32)

将指定字符数组中的一组字符编码为指定的字节数组。

GetBytes(Char[], Int32, Int32)

在派生类中重写时,将指定字符数组中的一组字符编码为字节序列。

(继承自 Encoding)
GetBytes(Char[])

在派生类中重写时,将指定字符数组中的所有字符编码为字节序列。

(继承自 Encoding)
GetBytes(Char*, Int32, Byte*, Int32)

将一组从指定字符指针开始的字符编码为从指定字节指针开始存储的字节序列。

GetBytes(ReadOnlySpan<Char>, Span<Byte>)

将指定的字符范围编码为指定的字节范围。

GetBytes(ReadOnlySpan<Char>, Span<Byte>)

在派生类中重写时,将字节范围编码为指定只读范围中的一组字符。

(继承自 Encoding)
GetBytes(String, Int32, Int32, Byte[], Int32)

将指定 String 字符集编码为指定的字节数组。

GetBytes(String, Int32, Int32)

在派生类中重写时,从指定的count字符串开始,编码为由指定字符串中指定的index字符数的字节数组。

(继承自 Encoding)
GetBytes(String)

将指定 String 对象中的字符编码为字节序列。

GetBytes(String)

在派生类中重写时,将指定字符串中的所有字符编码为字节序列。

(继承自 Encoding)
GetCharCount(Byte[], Int32, Int32)

计算通过解码指定字节数组中的字节序列生成的字符数。

GetCharCount(Byte[])

在派生类中重写时,计算通过解码指定字节数组中的所有字节生成的字符数。

(继承自 Encoding)
GetCharCount(Byte*, Int32)

计算通过解码从指定字节指针开始的字节序列生成的字符数。

GetCharCount(ReadOnlySpan<Byte>)

计算通过解码指定的字节范围生成的字符数。

GetCharCount(ReadOnlySpan<Byte>)

在派生类中重写时,计算通过解码提供的只读字节范围生成的字符数。

(继承自 Encoding)
GetChars(Byte[], Int32, Int32, Char[], Int32)

将指定字节数组中的字节序列解码为指定的字符数组。

GetChars(Byte[], Int32, Int32)

在派生类中重写时,将指定字节数组中的字节序列解码为一组字符。

(继承自 Encoding)
GetChars(Byte[])

在派生类中重写时,将指定字节数组中的所有字节解码为一组字符。

(继承自 Encoding)
GetChars(Byte*, Int32, Char*, Int32)

将从指定字节指针开始的字节序列解码为从指定字符指针开始存储的一组字符。

GetChars(ReadOnlySpan<Byte>, Span<Char>)

将指定的字节范围解码为指定的字符范围。

GetChars(ReadOnlySpan<Byte>, Span<Char>)

在派生类中重写时,将指定只读字节范围中的所有字节解码为字符范围。

(继承自 Encoding)
GetDecoder()

获取将 UTF-8 编码的字节序列转换为 Unicode 字符序列的解码器。

GetEncoder()

获取将 Unicode 字符序列转换为 UTF-8 编码字节序列的编码器。

GetHashCode()

返回当前实例的哈希代码。

GetMaxByteCount(Int32)

计算通过编码指定字符数生成的最大字节数。

GetMaxCharCount(Int32)

计算通过解码指定字节数生成的最大字符数。

GetPreamble()

如果编码对象配置为提供一个,则返回以 UTF-8 格式编码的 UTF8Encoding Unicode 字节顺序标记。

GetString(Byte[], Int32, Int32)

将字节数组中的字节范围解码为字符串。

GetString(Byte[], Int32, Int32)

在派生类中重写时,将指定字节数组中的字节序列解码为字符串。

(继承自 Encoding)
GetString(Byte[])

在派生类中重写时,将指定字节数组中的所有字节解码为字符串。

(继承自 Encoding)
GetString(Byte*, Int32)

在派生类中重写时,将从指定地址开始的指定字节数解码为字符串。

(继承自 Encoding)
GetString(ReadOnlySpan<Byte>)

在派生类中重写时,将指定字节范围中的所有字节解码为字符串。

(继承自 Encoding)
GetType()

获取当前实例的 Type

(继承自 Object)
IsAlwaysNormalized()

获取一个值,该值指示当前编码是否始终使用默认规范化形式进行规范化。

(继承自 Encoding)
IsAlwaysNormalized(NormalizationForm)

在派生类中重写时,获取一个值,该值指示当前编码是否始终使用指定的规范化形式进行规范化。

(继承自 Encoding)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
ToString()

返回一个表示当前对象的字符串。

(继承自 Object)
TryGetBytes(ReadOnlySpan<Char>, Span<Byte>, Int32)

如果目标足够大,则编码为指定只读范围中的一组字符的字节范围。

TryGetChars(ReadOnlySpan<Byte>, Span<Char>, Int32)

如果目标足够大,则从指定的只读范围将字符范围解码为一组字节。

扩展方法

名称 说明
GetBytes(Encoding, ReadOnlySequence<Char>, IBufferWriter<Byte>)

使用指定的ReadOnlySequence<T>byteEncoding值解码指定的值,并将结果writer写入到 。

GetBytes(Encoding, ReadOnlySequence<Char>, Span<Byte>)

使用指定的ReadOnlySequence<T>值对指定byteEncoding值进行编码,并将结果输出到 bytes

GetBytes(Encoding, ReadOnlySequence<Char>)

使用指定的ReadOnlySequence<T>数组将指定的Byte值编码为Encoding数组。

GetBytes(Encoding, ReadOnlySpan<Char>, IBufferWriter<Byte>)

使用指定的ReadOnlySpan<T>值对指定byteEncoding项进行编码,并将结果writer写入到 。

GetChars(Encoding, ReadOnlySequence<Byte>, IBufferWriter<Char>)

使用指定的ReadOnlySequence<T>charEncoding值解码指定的值,并将结果writer写入到 。

GetChars(Encoding, ReadOnlySequence<Byte>, Span<Char>)

使用指定的ReadOnlySequence<T>charEncoding值解码指定的值,并将结果输出到 。chars

GetChars(Encoding, ReadOnlySpan<Byte>, IBufferWriter<Char>)

使用指定的ReadOnlySpan<T>charEncoding值解码指定的值,并将结果writer写入到 。

GetString(Encoding, ReadOnlySequence<Byte>)

使用指定的值将指定的 ReadOnlySequence<T> 值解码为 String 指定的 Encoding

适用于

另请参阅