Encoding.GetEncoding 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
返回指定代码页的编码。
重载
GetEncoding(Int32) |
返回与指定代码页标识符关联的编码。 |
GetEncoding(String) |
返回与指定代码页名称关联的编码。 |
GetEncoding(Int32, EncoderFallback, DecoderFallback) |
返回与指定代码页标识符关联的编码。 参数指定一个错误处理程序,用于处理无法编码的字符和无法解码的字节序列。 |
GetEncoding(String, EncoderFallback, DecoderFallback) |
返回与指定代码页名称关联的编码。 参数指定一个错误处理程序,用于处理无法编码的字符和无法解码的字节序列。 |
GetEncoding(Int32)
- Source:
- Encoding.cs
- Source:
- Encoding.cs
- Source:
- Encoding.cs
返回与指定代码页标识符关联的编码。
public:
static System::Text::Encoding ^ GetEncoding(int codepage);
public static System.Text.Encoding GetEncoding (int codepage);
static member GetEncoding : int -> System.Text.Encoding
Public Shared Function GetEncoding (codepage As Integer) As Encoding
参数
返回
与指定代码页关联的编码。
例外
codepage
小于零或大于 65535。
基础平台不支持 codepage
。
基础平台不支持 codepage
。
示例
下面的示例获取相同编码的两个实例(一个按代码页,另一个按名称),并检查它们是否相等。
using namespace System;
using namespace System::Text;
int main()
{
// Get a UTF-32 encoding by codepage.
Encoding^ e1 = Encoding::GetEncoding( 12000 );
// Get a UTF-32 encoding by name.
Encoding^ e2 = Encoding::GetEncoding( "utf-32" );
// Check their equality.
Console::WriteLine( "e1 equals e2? {0}", e1->Equals( e2 ) );
}
/*
This code produces the following output.
e1 equals e2? True
*/
using System;
using System.Text;
public class SamplesEncoding {
public static void Main() {
// Get a UTF-32 encoding by codepage.
Encoding e1 = Encoding.GetEncoding( 12000 );
// Get a UTF-32 encoding by name.
Encoding e2 = Encoding.GetEncoding( "utf-32" );
// Check their equality.
Console.WriteLine( "e1 equals e2? {0}", e1.Equals( e2 ) );
}
}
/*
This code produces the following output.
e1 equals e2? True
*/
Imports System.Text
Public Class SamplesEncoding
Public Shared Sub Main()
' Get a UTF-32 encoding by codepage.
Dim e1 As Encoding = Encoding.GetEncoding(12000)
' Get a UTF-32 encoding by name.
Dim e2 As Encoding = Encoding.GetEncoding("utf-32")
' Check their equality.
Console.WriteLine("e1 equals e2? {0}", e1.Equals(e2))
End Sub
End Class
'This code produces the following output.
'
'e1 equals e2? True
注解
回退处理程序依赖于的编码类型 codepage
。 如果 codepage
是代码页或双字节字符集(DBCS)编码,则使用最佳回退处理程序。 否则,将使用替代回退处理程序。 这些回退处理程序可能不适合您的应用程序。 若要指定由指定的编码使用的回退处理程序 codepage
,可以调用 GetEncoding(Int32, EncoderFallback, DecoderFallback) 重载。
在 .NET Framework 中, GetEncoding 方法依赖于基础平台来支持大多数代码页。 但是,.NET Framework 本机支持某些编码。 有关代码页的列表,请参阅编码列表。 在 .NET Core 中, GetEncoding 方法返回 .Net core 本机支持的编码。 在这两种 .NET 实现上,都可以调用 GetEncodings 方法来获取 EncodingInfo 对象的数组,这些对象包含有关所有可用的编码的信息。
除了本机在 .NET Core 上可用或在 .NET Framework 的特定平台版本上受支持的编码以外,该 GetEncoding 方法还返回通过注册对象提供的任何其他编码 EncodingProvider 。 如果多个对象已注册了相同的编码 EncodingProvider ,则此方法将返回最后一个注册的。
还可以为参数提供0值 codepage
。 其确切行为取决于是否已通过注册对象提供了任何编码 EncodingProvider :
如果注册了一个或多个编码提供程序,则它会返回上次注册的提供程序的编码,该提供程序已选择在向 GetEncoding 方法传递
codepage
参数0时返回编码。在 .NET Framework 上,如果没有注册任何编码提供程序,如果 CodePagesEncodingProvider 是注册的编码提供程序,或者如果没有已注册的编码提供程序处理
codepage
值0,则返回操作系统的活动代码页。 若要确定 Windows 系统上的活动代码页,请从 .NET Framework调用 Windows GetACP 函数。在 .NET Core 中,如果未注册任何编码提供程序,或者没有任何注册的编码提供程序处理
codepage
值0,则返回 UTF8Encoding 。
注意
- 某些不受支持的代码页会 ArgumentException 引发,而另一些则 NotSupportedException 导致。 因此,您的代码必须捕获 "异常" 部分中指示的所有异常。
- 在 .NET 5 及更高版本中,不支持表示 UTF-7 的代码页标识符
65000
。
注意
ANSI 代码页在不同计算机上可能不同,并且可以在一台计算机上更改,导致数据损坏。 出于此原因,如果活动代码页是 ANSI 代码页,则不建议使用返回的默认代码页对数据进行编码和解码 Encoding.GetEncoding(0)
。 为获得最一致的结果,应使用 Unicode 编码,例如 UTF-8 (代码页65001)或 UTF-16,而不是使用特定的代码页。
GetEncoding使用默认设置返回缓存的实例。 应使用派生类的构造函数获取具有不同设置的实例。 例如, UTF32Encoding 类提供可让你启用错误检测的构造函数。
另请参阅
适用于
GetEncoding(String)
- Source:
- Encoding.cs
- Source:
- Encoding.cs
- Source:
- Encoding.cs
返回与指定代码页名称关联的编码。
public:
static System::Text::Encoding ^ GetEncoding(System::String ^ name);
public static System.Text.Encoding GetEncoding (string name);
static member GetEncoding : string -> System.Text.Encoding
Public Shared Function GetEncoding (name As String) As Encoding
参数
返回
与指定的代码页关联的编码。
例外
示例
下面的示例获取相同编码的两个实例(一个按代码页,另一个按名称),并检查它们是否相等。
using namespace System;
using namespace System::Text;
int main()
{
// Get a UTF-32 encoding by codepage.
Encoding^ e1 = Encoding::GetEncoding( 12000 );
// Get a UTF-32 encoding by name.
Encoding^ e2 = Encoding::GetEncoding( "utf-32" );
// Check their equality.
Console::WriteLine( "e1 equals e2? {0}", e1->Equals( e2 ) );
}
/*
This code produces the following output.
e1 equals e2? True
*/
using System;
using System.Text;
public class SamplesEncoding {
public static void Main() {
// Get a UTF-32 encoding by codepage.
Encoding e1 = Encoding.GetEncoding( 12000 );
// Get a UTF-32 encoding by name.
Encoding e2 = Encoding.GetEncoding( "utf-32" );
// Check their equality.
Console.WriteLine( "e1 equals e2? {0}", e1.Equals( e2 ) );
}
}
/*
This code produces the following output.
e1 equals e2? True
*/
Imports System.Text
Public Class SamplesEncoding
Public Shared Sub Main()
' Get a UTF-32 encoding by codepage.
Dim e1 As Encoding = Encoding.GetEncoding(12000)
' Get a UTF-32 encoding by name.
Dim e2 As Encoding = Encoding.GetEncoding("utf-32")
' Check their equality.
Console.WriteLine("e1 equals e2? {0}", e1.Equals(e2))
End Sub
End Class
'This code produces the following output.
'
'e1 equals e2? True
注解
回退处理程序依赖于的编码类型 name
。 如果 name
是代码页或双字节字符集(DBCS)编码,则使用最佳回退处理程序。 否则,将使用替代回退处理程序。 这些回退处理程序可能不适合您的应用程序。 若要指定由指定的编码使用的回退处理程序 name
,可以调用 GetEncoding(String, EncoderFallback, DecoderFallback) 重载。
在 .NET Framework 中, GetEncoding 方法依赖于基础平台来支持大多数代码页。 但是,.NET Framework 本机支持某些编码。 有关代码页的列表,请参阅编码列表。 在 .NET Core 中, GetEncoding 方法返回 .Net core 本机支持的编码。 在这两种 .NET 实现上,都可以调用 GetEncodings 方法来获取 EncodingInfo 对象的数组,这些对象包含有关所有可用的编码的信息。
除了本机在 .NET Core 上可用或在 .NET Framework 的特定平台版本上受支持的编码以外,该 GetEncoding 方法还返回通过注册对象提供的任何其他编码 EncodingProvider 。 如果多个对象已注册了相同的编码 EncodingProvider ,则此方法将返回最后一个注册的。
在 .NET 5 及更高版本中,不支持代码页名称 utf-7
。
注意
在不同的计算机上,ANSI 代码页可能会不同,或者可以针对一台计算机进行更改,从而导致数据损坏。 为获得最一致的结果,请使用 Unicode,如 UTF-8 (代码页65001)或 UTF-16,而不是特定的代码页。
GetEncoding使用默认设置返回缓存的实例。 应使用派生类的构造函数获取具有不同设置的实例。 例如, UTF32Encoding 类提供可让你启用错误检测的构造函数。
另请参阅
适用于
GetEncoding(Int32, EncoderFallback, DecoderFallback)
- Source:
- Encoding.cs
- Source:
- Encoding.cs
- Source:
- Encoding.cs
返回与指定代码页标识符关联的编码。 参数指定一个错误处理程序,用于处理无法编码的字符和无法解码的字节序列。
public:
static System::Text::Encoding ^ GetEncoding(int codepage, System::Text::EncoderFallback ^ encoderFallback, System::Text::DecoderFallback ^ decoderFallback);
public static System.Text.Encoding GetEncoding (int codepage, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback);
static member GetEncoding : int * System.Text.EncoderFallback * System.Text.DecoderFallback -> System.Text.Encoding
Public Shared Function GetEncoding (codepage As Integer, encoderFallback As EncoderFallback, decoderFallback As DecoderFallback) As Encoding
参数
- encoderFallback
- EncoderFallback
一个对象,在无法用当前编码对字符进行编码时,该对象可用来提供错误处理过程。
- decoderFallback
- DecoderFallback
一个对象,在无法用当前编码对字节序列进行解码时,该对象可用来提供错误处理过程。
返回
与指定代码页关联的编码。
例外
codepage
小于零或大于 65535。
基础平台不支持 codepage
。
基础平台不支持 codepage
。
示例
下面的示例演示 Encoding.GetEncoding(String, EncoderFallback, DecoderFallback) 方法。
// This example demonstrates the EncoderReplacementFallback class.
using namespace System;
using namespace System::Text;
int main()
{
// Create an encoding, which is equivalent to calling the
// ASCIIEncoding class constructor.
// The EncoderReplacementFallback parameter specifies that the
// string, "(unknown)", replace characters that cannot be encoded.
// A decoder replacement fallback is also specified, but in this
// code example the decoding operation cannot fail.
Encoding^ ascii = Encoding::GetEncoding("us-ascii",
gcnew EncoderReplacementFallback("(unknown)"),
gcnew DecoderReplacementFallback("(error)"));
// The input string consists of the Unicode characters LEFT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT
// POINTING DOUBLE ANGLE QUOTATION MARK (U+00BB).
// The encoding can only encode characters in the US-ASCII range of
// U+0000 through U+007F. Consequently, the characters bracketing the
// 'X' character are replaced with the fallback replacement string,
// "(unknown)".
String^ inputString = "\u00abX\u00bb";
String^ decodedString;
String^ twoNewLines = Environment::NewLine + Environment::NewLine;
array <Byte>^ encodedBytes =
gcnew array<Byte>(ascii->GetByteCount(inputString));
int numberOfEncodedBytes = 0;
// ---------------------------------------------------------------------
// Display the name of the encoding.
Console::WriteLine("The name of the encoding is \"{0}\".{1}",
ascii->WebName, Environment::NewLine);
// Display the input string in text.
Console::WriteLine("Input string ({0} characters): \"{1}\"",
inputString->Length, inputString);
// Display the input string in hexadecimal.
Console::Write("Input string in hexadecimal: ");
for each (char c in inputString)
{
Console::Write("0x{0:X2} ", c);
}
Console::Write(twoNewLines);
// ---------------------------------------------------------------------
// Encode the input string.
Console::WriteLine("Encode the input string...");
numberOfEncodedBytes = ascii->GetBytes(inputString, 0, inputString->Length,
encodedBytes, 0);
// Display the encoded bytes.
Console::WriteLine("Encoded bytes in hexadecimal ({0} bytes):{1}",
numberOfEncodedBytes, Environment::NewLine);
for(int i = 0; i < encodedBytes->Length; i++)
{
Console::Write("0x{0:X2} ", encodedBytes[i]);
if(((i + 1) % 6) == 0)
{
Console::WriteLine();
}
}
Console::Write(twoNewLines);
// ---------------------------------------------------------------------
// Decode the encoded bytes, yielding a reconstituted string.
Console::WriteLine("Decode the encoded bytes...");
decodedString = ascii->GetString(encodedBytes);
// Display the input string and the decoded string for comparison.
Console::WriteLine("Input string: \"{0}\"", inputString);
Console::WriteLine("Decoded string:\"{0}\"", decodedString);
}
/*
This code example produces the following results:
The name of the encoding is "us-ascii".
Input string (3 characters): "X"
Input string in hexadecimal: 0xAB 0x58 0xBB
Encode the input string...
Encoded bytes in hexadecimal (19 bytes):
0x28 0x75 0x6E 0x6B 0x6E 0x6F
0x77 0x6E 0x29 0x58 0x28 0x75
0x6E 0x6B 0x6E 0x6F 0x77 0x6E
0x29
Decode the encoded bytes...
Input string: "X"
Decoded string:"(unknown)X(unknown)"
*/
// This example demonstrates the EncoderReplacementFallback class.
using System;
using System.Text;
class Sample
{
public static void Main()
{
// Create an encoding, which is equivalent to calling the
// ASCIIEncoding class constructor.
// The EncoderReplacementFallback parameter specifies that the
// string, "(unknown)", replace characters that cannot be encoded.
// A decoder replacement fallback is also specified, but in this
// code example the decoding operation cannot fail.
Encoding ae = Encoding.GetEncoding(
"us-ascii",
new EncoderReplacementFallback("(unknown)"),
new DecoderReplacementFallback("(error)"));
// The input string consists of the Unicode characters LEFT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00BB).
// The encoding can only encode characters in the US-ASCII range of U+0000
// through U+007F. Consequently, the characters bracketing the 'X' character
// are replaced with the fallback replacement string, "(unknown)".
string inputString = "\u00abX\u00bb";
string decodedString;
string twoNewLines = "\n\n";
byte[] encodedBytes = new byte[ae.GetByteCount(inputString)];
int numberOfEncodedBytes = 0;
int ix = 0;
// --------------------------------------------------------------------------
// Display the name of the encoding.
Console.WriteLine("The name of the encoding is \"{0}\".\n", ae.WebName);
// Display the input string in text.
Console.WriteLine("Input string ({0} characters): \"{1}\"",
inputString.Length, inputString);
// Display the input string in hexadecimal.
Console.Write("Input string in hexadecimal: ");
foreach (char c in inputString.ToCharArray())
{
Console.Write("0x{0:X2} ", (int)c);
}
Console.Write(twoNewLines);
// --------------------------------------------------------------------------
// Encode the input string.
Console.WriteLine("Encode the input string...");
numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length,
encodedBytes, 0);
// Display the encoded bytes.
Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):\n",
numberOfEncodedBytes);
ix = 0;
foreach (byte b in encodedBytes)
{
Console.Write("0x{0:X2} ", (int)b);
ix++;
if (0 == ix % 6) Console.WriteLine();
}
Console.Write(twoNewLines);
// --------------------------------------------------------------------------
// Decode the encoded bytes, yielding a reconstituted string.
Console.WriteLine("Decode the encoded bytes...");
decodedString = ae.GetString(encodedBytes);
// Display the input string and the decoded string for comparison.
Console.WriteLine("Input string: \"{0}\"", inputString);
Console.WriteLine("Decoded string:\"{0}\"", decodedString);
}
}
/*
This code example produces the following results:
The name of the encoding is "us-ascii".
Input string (3 characters): "«X»"
Input string in hexadecimal: 0xAB 0x58 0xBB
Encode the input string...
Encoded bytes in hexadecimal (19 bytes):
0x28 0x75 0x6E 0x6B 0x6E 0x6F
0x77 0x6E 0x29 0x58 0x28 0x75
0x6E 0x6B 0x6E 0x6F 0x77 0x6E
0x29
Decode the encoded bytes...
Input string: "«X»"
Decoded string:"(unknown)X(unknown)"
*/
' This example demonstrates the EncoderReplacementFallback class.
Imports System.Text
Class Sample
Public Shared Sub Main()
' Create an encoding, which is equivalent to calling the
' ASCIIEncoding class constructor.
' The EncoderReplacementFallback parameter specifies that the
' string, "(unknown)", replace characters that cannot be encoded.
' A decoder replacement fallback is also specified, but in this
' code example the decoding operation cannot fail.
Dim erf As New EncoderReplacementFallback("(unknown)")
Dim drf As New DecoderReplacementFallback("(error)")
Dim ae As Encoding = Encoding.GetEncoding("us-ascii", erf, drf)
' The input string consists of the Unicode characters LEFT POINTING
' DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING
' DOUBLE ANGLE QUOTATION MARK (U+00BB).
' The encoding can only encode characters in the US-ASCII range of U+0000
' through U+007F. Consequently, the characters bracketing the 'X' character
' are replaced with the fallback replacement string, "(unknown)".
Dim inputString As String = "«X»"
Dim decodedString As String
Dim twoNewLines As String = vbCrLf & vbCrLf
Dim ix As Integer = 0
Dim numberOfEncodedBytes As Integer = ae.GetByteCount(inputString)
' Counteract the compiler adding an extra byte to the array.
Dim encodedBytes(numberOfEncodedBytes - 1) As Byte
' --------------------------------------------------------------------------
' Display the name of the encoding.
Console.WriteLine("The name of the encoding is ""{0}""." & vbCrLf, ae.WebName)
' Display the input string in text.
Console.WriteLine("Input string ({0} characters): ""{1}""", _
inputString.Length, inputString)
' Display the input string in hexadecimal.
' Each element is converted to an integer with Convert.ToInt32.
Console.Write("Input string in hexadecimal: ")
Dim c As Char
For Each c In inputString.ToCharArray()
Console.Write("0x{0:X2} ", Convert.ToInt32(c))
Next c
Console.Write(twoNewLines)
' --------------------------------------------------------------------------
' Encode the input string.
Console.WriteLine("Encode the input string...")
numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length, _
encodedBytes, 0)
' Display the encoded bytes.
' Each element is converted to an integer with Convert.ToInt32.
Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):" & vbCrLf, _
numberOfEncodedBytes)
ix = 0
Dim b As Byte
For Each b In encodedBytes
Console.Write("0x{0:X2} ", Convert.ToInt32(b))
ix += 1
If 0 = ix Mod 6 Then
Console.WriteLine()
End If
Next b
Console.Write(twoNewLines)
' --------------------------------------------------------------------------
' Decode the encoded bytes, yielding a reconstituted string.
Console.WriteLine("Decode the encoded bytes...")
decodedString = ae.GetString(encodedBytes)
' Display the input string and the decoded string for comparison.
Console.WriteLine("Input string: ""{0}""", inputString)
Console.WriteLine("Decoded string:""{0}""", decodedString)
End Sub
End Class
'
'This code example produces the following results:
'
'The name of the encoding is "us-ascii".
'
'Input string (3 characters): "X"
'Input string in hexadecimal: 0xAB 0x58 0xBB
'
'Encode the input string...
'Encoded bytes in hexadecimal (19 bytes):
'
'0x28 0x75 0x6E 0x6B 0x6E 0x6F
'0x77 0x6E 0x29 0x58 0x28 0x75
'0x6E 0x6B 0x6E 0x6F 0x77 0x6E
'0x29
'
'Decode the encoded bytes...
'Input string: "X"
'Decoded string:"(unknown)X(unknown)"
'
注解
注意
- 某些不受支持的代码页会 ArgumentException 引发异常,而其他代码页则导致引发异常 NotSupportedException 。 因此,您的代码必须捕获 "异常" 部分中指示的所有异常。
- 在 .NET 5 及更高版本中,不支持表示 UTF-7 的代码页标识符
65000
。
在 .NET Framework 中, GetEncoding 方法依赖于基础平台来支持大多数代码页。 但是,.NET Framework 本机支持某些编码。 有关代码页的列表,请参阅编码列表。 在 .NET Core 中, GetEncoding 方法返回 .Net core 本机支持的编码。 在这两种 .NET 实现上,都可以调用 GetEncodings 方法来获取 EncodingInfo 对象的数组,这些对象包含有关所有可用的编码的信息。
除了本机在 .NET Core 上可用或在 .NET Framework 的特定平台版本上受支持的编码以外,该 GetEncoding 方法还返回通过注册对象提供的任何其他编码 EncodingProvider 。 如果多个对象已注册了相同的编码 EncodingProvider ,则此方法将返回最后一个注册的。
还可以为参数提供0值 codepage
。 其确切行为取决于是否已通过注册对象提供了任何编码 EncodingProvider :
如果注册了一个或多个编码提供程序,则它会返回上次注册的提供程序的编码,该提供程序已选择在向 GetEncoding 方法传递
codepage
参数0时返回编码。在 .NET Framework 上,如果没有注册任何编码提供程序,如果 CodePagesEncodingProvider 是注册的编码提供程序,或者如果没有已注册的编码提供程序处理
codepage
值0,则返回活动代码页。在 .NET Core 中,如果未注册任何编码提供程序,或者没有任何注册的编码提供程序处理
codepage
值0,则返回 UTF8Encoding 编码。
注意
ANSI 代码页在不同计算机上可能不同,并且可以在一台计算机上更改,导致数据损坏。 出于此原因,如果活动代码页是 ANSI 代码页,则不建议使用返回的默认代码页对数据进行编码和解码 Encoding.GetEncoding(0)
。 为获得最一致的结果,应使用 Unicode,如 UTF-8 (代码页65001)或 UTF-16,而不是特定的代码页。
若要获取与活动代码页关联的编码,可以为 参数提供值 0codepage
,或者如果代码在.NET Framework上运行,则检索 属性的值Encoding.Default。 若要确定当前活动代码页,请从 .NET Framework 调用 Windows GetACP 函数。
GetEncoding使用默认设置返回缓存的实例。 应使用派生类的构造函数获取具有不同设置的实例。 例如, UTF32Encoding 类提供可让你启用错误检测的构造函数。
另请参阅
适用于
GetEncoding(String, EncoderFallback, DecoderFallback)
- Source:
- Encoding.cs
- Source:
- Encoding.cs
- Source:
- Encoding.cs
返回与指定代码页名称关联的编码。 参数指定一个错误处理程序,用于处理无法编码的字符和无法解码的字节序列。
public:
static System::Text::Encoding ^ GetEncoding(System::String ^ name, System::Text::EncoderFallback ^ encoderFallback, System::Text::DecoderFallback ^ decoderFallback);
public static System.Text.Encoding GetEncoding (string name, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback);
static member GetEncoding : string * System.Text.EncoderFallback * System.Text.DecoderFallback -> System.Text.Encoding
Public Shared Function GetEncoding (name As String, encoderFallback As EncoderFallback, decoderFallback As DecoderFallback) As Encoding
参数
- encoderFallback
- EncoderFallback
一个对象,在无法用当前编码对字符进行编码时,该对象可用来提供错误处理过程。
- decoderFallback
- DecoderFallback
一个对象,在无法用当前编码对字节序列进行解码时,该对象可用来提供错误处理过程。
返回
与指定代码页关联的编码。
例外
示例
下面的示例演示 Encoding.GetEncoding(String, EncoderFallback, DecoderFallback) 方法。
// This example demonstrates the EncoderReplacementFallback class.
using namespace System;
using namespace System::Text;
int main()
{
// Create an encoding, which is equivalent to calling the
// ASCIIEncoding class constructor.
// The EncoderReplacementFallback parameter specifies that the
// string, "(unknown)", replace characters that cannot be encoded.
// A decoder replacement fallback is also specified, but in this
// code example the decoding operation cannot fail.
Encoding^ ascii = Encoding::GetEncoding("us-ascii",
gcnew EncoderReplacementFallback("(unknown)"),
gcnew DecoderReplacementFallback("(error)"));
// The input string consists of the Unicode characters LEFT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT
// POINTING DOUBLE ANGLE QUOTATION MARK (U+00BB).
// The encoding can only encode characters in the US-ASCII range of
// U+0000 through U+007F. Consequently, the characters bracketing the
// 'X' character are replaced with the fallback replacement string,
// "(unknown)".
String^ inputString = "\u00abX\u00bb";
String^ decodedString;
String^ twoNewLines = Environment::NewLine + Environment::NewLine;
array <Byte>^ encodedBytes =
gcnew array<Byte>(ascii->GetByteCount(inputString));
int numberOfEncodedBytes = 0;
// ---------------------------------------------------------------------
// Display the name of the encoding.
Console::WriteLine("The name of the encoding is \"{0}\".{1}",
ascii->WebName, Environment::NewLine);
// Display the input string in text.
Console::WriteLine("Input string ({0} characters): \"{1}\"",
inputString->Length, inputString);
// Display the input string in hexadecimal.
Console::Write("Input string in hexadecimal: ");
for each (char c in inputString)
{
Console::Write("0x{0:X2} ", c);
}
Console::Write(twoNewLines);
// ---------------------------------------------------------------------
// Encode the input string.
Console::WriteLine("Encode the input string...");
numberOfEncodedBytes = ascii->GetBytes(inputString, 0, inputString->Length,
encodedBytes, 0);
// Display the encoded bytes.
Console::WriteLine("Encoded bytes in hexadecimal ({0} bytes):{1}",
numberOfEncodedBytes, Environment::NewLine);
for(int i = 0; i < encodedBytes->Length; i++)
{
Console::Write("0x{0:X2} ", encodedBytes[i]);
if(((i + 1) % 6) == 0)
{
Console::WriteLine();
}
}
Console::Write(twoNewLines);
// ---------------------------------------------------------------------
// Decode the encoded bytes, yielding a reconstituted string.
Console::WriteLine("Decode the encoded bytes...");
decodedString = ascii->GetString(encodedBytes);
// Display the input string and the decoded string for comparison.
Console::WriteLine("Input string: \"{0}\"", inputString);
Console::WriteLine("Decoded string:\"{0}\"", decodedString);
}
/*
This code example produces the following results:
The name of the encoding is "us-ascii".
Input string (3 characters): "X"
Input string in hexadecimal: 0xAB 0x58 0xBB
Encode the input string...
Encoded bytes in hexadecimal (19 bytes):
0x28 0x75 0x6E 0x6B 0x6E 0x6F
0x77 0x6E 0x29 0x58 0x28 0x75
0x6E 0x6B 0x6E 0x6F 0x77 0x6E
0x29
Decode the encoded bytes...
Input string: "X"
Decoded string:"(unknown)X(unknown)"
*/
// This example demonstrates the EncoderReplacementFallback class.
using System;
using System.Text;
class Sample
{
public static void Main()
{
// Create an encoding, which is equivalent to calling the
// ASCIIEncoding class constructor.
// The EncoderReplacementFallback parameter specifies that the
// string, "(unknown)", replace characters that cannot be encoded.
// A decoder replacement fallback is also specified, but in this
// code example the decoding operation cannot fail.
Encoding ae = Encoding.GetEncoding(
"us-ascii",
new EncoderReplacementFallback("(unknown)"),
new DecoderReplacementFallback("(error)"));
// The input string consists of the Unicode characters LEFT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00BB).
// The encoding can only encode characters in the US-ASCII range of U+0000
// through U+007F. Consequently, the characters bracketing the 'X' character
// are replaced with the fallback replacement string, "(unknown)".
string inputString = "\u00abX\u00bb";
string decodedString;
string twoNewLines = "\n\n";
byte[] encodedBytes = new byte[ae.GetByteCount(inputString)];
int numberOfEncodedBytes = 0;
int ix = 0;
// --------------------------------------------------------------------------
// Display the name of the encoding.
Console.WriteLine("The name of the encoding is \"{0}\".\n", ae.WebName);
// Display the input string in text.
Console.WriteLine("Input string ({0} characters): \"{1}\"",
inputString.Length, inputString);
// Display the input string in hexadecimal.
Console.Write("Input string in hexadecimal: ");
foreach (char c in inputString.ToCharArray())
{
Console.Write("0x{0:X2} ", (int)c);
}
Console.Write(twoNewLines);
// --------------------------------------------------------------------------
// Encode the input string.
Console.WriteLine("Encode the input string...");
numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length,
encodedBytes, 0);
// Display the encoded bytes.
Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):\n",
numberOfEncodedBytes);
ix = 0;
foreach (byte b in encodedBytes)
{
Console.Write("0x{0:X2} ", (int)b);
ix++;
if (0 == ix % 6) Console.WriteLine();
}
Console.Write(twoNewLines);
// --------------------------------------------------------------------------
// Decode the encoded bytes, yielding a reconstituted string.
Console.WriteLine("Decode the encoded bytes...");
decodedString = ae.GetString(encodedBytes);
// Display the input string and the decoded string for comparison.
Console.WriteLine("Input string: \"{0}\"", inputString);
Console.WriteLine("Decoded string:\"{0}\"", decodedString);
}
}
/*
This code example produces the following results:
The name of the encoding is "us-ascii".
Input string (3 characters): "«X»"
Input string in hexadecimal: 0xAB 0x58 0xBB
Encode the input string...
Encoded bytes in hexadecimal (19 bytes):
0x28 0x75 0x6E 0x6B 0x6E 0x6F
0x77 0x6E 0x29 0x58 0x28 0x75
0x6E 0x6B 0x6E 0x6F 0x77 0x6E
0x29
Decode the encoded bytes...
Input string: "«X»"
Decoded string:"(unknown)X(unknown)"
*/
' This example demonstrates the EncoderReplacementFallback class.
Imports System.Text
Class Sample
Public Shared Sub Main()
' Create an encoding, which is equivalent to calling the
' ASCIIEncoding class constructor.
' The EncoderReplacementFallback parameter specifies that the
' string, "(unknown)", replace characters that cannot be encoded.
' A decoder replacement fallback is also specified, but in this
' code example the decoding operation cannot fail.
Dim erf As New EncoderReplacementFallback("(unknown)")
Dim drf As New DecoderReplacementFallback("(error)")
Dim ae As Encoding = Encoding.GetEncoding("us-ascii", erf, drf)
' The input string consists of the Unicode characters LEFT POINTING
' DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING
' DOUBLE ANGLE QUOTATION MARK (U+00BB).
' The encoding can only encode characters in the US-ASCII range of U+0000
' through U+007F. Consequently, the characters bracketing the 'X' character
' are replaced with the fallback replacement string, "(unknown)".
Dim inputString As String = "«X»"
Dim decodedString As String
Dim twoNewLines As String = vbCrLf & vbCrLf
Dim ix As Integer = 0
Dim numberOfEncodedBytes As Integer = ae.GetByteCount(inputString)
' Counteract the compiler adding an extra byte to the array.
Dim encodedBytes(numberOfEncodedBytes - 1) As Byte
' --------------------------------------------------------------------------
' Display the name of the encoding.
Console.WriteLine("The name of the encoding is ""{0}""." & vbCrLf, ae.WebName)
' Display the input string in text.
Console.WriteLine("Input string ({0} characters): ""{1}""", _
inputString.Length, inputString)
' Display the input string in hexadecimal.
' Each element is converted to an integer with Convert.ToInt32.
Console.Write("Input string in hexadecimal: ")
Dim c As Char
For Each c In inputString.ToCharArray()
Console.Write("0x{0:X2} ", Convert.ToInt32(c))
Next c
Console.Write(twoNewLines)
' --------------------------------------------------------------------------
' Encode the input string.
Console.WriteLine("Encode the input string...")
numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length, _
encodedBytes, 0)
' Display the encoded bytes.
' Each element is converted to an integer with Convert.ToInt32.
Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):" & vbCrLf, _
numberOfEncodedBytes)
ix = 0
Dim b As Byte
For Each b In encodedBytes
Console.Write("0x{0:X2} ", Convert.ToInt32(b))
ix += 1
If 0 = ix Mod 6 Then
Console.WriteLine()
End If
Next b
Console.Write(twoNewLines)
' --------------------------------------------------------------------------
' Decode the encoded bytes, yielding a reconstituted string.
Console.WriteLine("Decode the encoded bytes...")
decodedString = ae.GetString(encodedBytes)
' Display the input string and the decoded string for comparison.
Console.WriteLine("Input string: ""{0}""", inputString)
Console.WriteLine("Decoded string:""{0}""", decodedString)
End Sub
End Class
'
'This code example produces the following results:
'
'The name of the encoding is "us-ascii".
'
'Input string (3 characters): "X"
'Input string in hexadecimal: 0xAB 0x58 0xBB
'
'Encode the input string...
'Encoded bytes in hexadecimal (19 bytes):
'
'0x28 0x75 0x6E 0x6B 0x6E 0x6F
'0x77 0x6E 0x29 0x58 0x28 0x75
'0x6E 0x6B 0x6E 0x6F 0x77 0x6E
'0x29
'
'Decode the encoded bytes...
'Input string: "X"
'Decoded string:"(unknown)X(unknown)"
'
注解
在 .NET Framework 中, GetEncoding 方法依赖于基础平台来支持大多数代码页。 但是,.NET Framework 本机支持某些编码。 有关代码页的列表,请参阅编码列表。 在 .NET Core 中, GetEncoding 方法返回 .Net core 本机支持的编码。 在这两种 .NET 实现上,都可以调用 GetEncodings 方法来获取 EncodingInfo 对象的数组,这些对象包含有关所有可用的编码的信息。
除了本机在 .NET Core 上可用或在 .NET Framework 的特定平台版本上受支持的编码以外,该 GetEncoding 方法还返回通过注册对象提供的任何其他编码 EncodingProvider 。 如果多个对象已注册了相同的编码 EncodingProvider ,则此方法将返回最后一个注册的。
在 .NET 5 及更高版本中,不支持代码页名称 utf-7
。
注意
ANSI 代码页在不同计算机上可能不同,并且可以在一台计算机上更改,导致数据损坏。 为获得最一致的结果,应使用 Unicode 编码,例如 UTF-8 (代码页65001)或 UTF-16,而不是使用特定的代码页。
GetEncoding使用默认设置返回缓存的实例。 应使用派生类的构造函数获取具有不同设置的实例。 例如, UTF32Encoding 类提供可让你启用错误检测的构造函数。