Encoding.GetEncoding 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
傳回指定字碼頁的編碼方式。
多載
GetEncoding(Int32) |
傳回與指定字碼頁識別項相關聯的編碼方式。 |
GetEncoding(String) |
傳回與指定字碼頁名稱相關聯的編碼方式。 |
GetEncoding(Int32, EncoderFallback, DecoderFallback) |
傳回與指定字碼頁識別項相關聯的編碼方式。 參數會針對無法編碼的字元以及無法解碼的位元組序列指定錯誤處理常式。 |
GetEncoding(String, EncoderFallback, DecoderFallback) |
傳回與指定字碼頁名稱相關聯的編碼方式。 參數會針對無法編碼的字元以及無法解碼的位元組序列指定錯誤處理常式。 |
GetEncoding(Int32)
- 來源:
- Encoding.cs
- 來源:
- Encoding.cs
- 來源:
- 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 物件已註冊相同的編碼方式,這個方法會傳回最後一個已註冊的編碼方式。
您也可以為 codepage
引數提供 0 的值。 其精確行為取決於註冊物件是否已經提供 EncodingProvider 任何編碼:
如果已註冊一或多個編碼提供者,它會傳回最後一個已註冊提供者的編碼方式,這個提供者在方法傳遞
codepage
引數為 0 時 GetEncoding ,會傳回編碼方式。在.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)
- 來源:
- Encoding.cs
- 來源:
- Encoding.cs
- 來源:
- 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)
- 來源:
- Encoding.cs
- 來源:
- Encoding.cs
- 來源:
- 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 物件已註冊相同的編碼方式,這個方法會傳回最後一個已註冊的編碼方式。
您也可以為 codepage
引數提供 0 的值。 其精確行為取決於註冊物件是否提供 EncodingProvider 任何編碼:
如果已註冊一或多個編碼提供者,它會傳回在方法傳遞
codepage
引數 0 時 GetEncoding ,選擇傳回編碼的最後一個已註冊提供者的編碼方式。在.NET Framework上,如果沒有註冊編碼提供者、如果 CodePagesEncodingProvider 是已註冊的編碼提供者,或沒有已註冊的編碼提供者處理
codepage
值為 0,則會傳回使用中的字碼頁。在 .NET Core 上,如果未註冊編碼提供者,或沒有已註冊的編碼提供者處理
codepage
0 值,則會傳 UTF8Encoding 回編碼。
注意
ANSI 字碼頁在不同的電腦上可能不同,而且可以在單一電腦上變更,導致資料損毀。 基於這個理由,如果使用中的字碼頁是 ANSI 字碼頁,則不建議使用 傳 Encoding.GetEncoding(0)
回的預設字碼頁編碼和解碼資料。 針對最一致的結果,您應該使用 Unicode,例如 UTF-8 (字碼頁 65001) 或 UTF-16,而不是特定的字碼頁。
若要取得與使用中字碼頁相關聯的編碼,您可以為 引數提供 0 codepage
的值,或者,如果您的程式碼是在 .NET Framework 上執行,請擷取 屬性的值 Encoding.Default 。 若要判斷目前的使用中字碼頁,請從 .NET Framework呼叫 Windows GetACP函式。
GetEncoding 會傳回具有預設設定的快取實例。 您應該使用衍生類別的建構函式來取得具有不同設定的實例。 例如,類別 UTF32Encoding 提供可讓您啟用錯誤偵測的建構函式。
另請參閱
適用於
GetEncoding(String, EncoderFallback, DecoderFallback)
- 來源:
- Encoding.cs
- 來源:
- Encoding.cs
- 來源:
- 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 提供可讓您啟用錯誤偵測的建構函式。