Encoding.GetEncoding Metoda

Definicja

Zwraca kodowanie dla określonej strony kodu.

Przeciążenia

GetEncoding(Int32)

Zwraca kodowanie skojarzone z określonym identyfikatorem strony kodu.

GetEncoding(String)

Zwraca kodowanie skojarzone z określoną nazwą strony kodowej.

GetEncoding(Int32, EncoderFallback, DecoderFallback)

Zwraca kodowanie skojarzone z określonym identyfikatorem strony kodu. Parametry określają procedurę obsługi błędów dla znaków, których nie można kodować i sekwencje bajtów, których nie można zdekodować.

GetEncoding(String, EncoderFallback, DecoderFallback)

Zwraca kodowanie skojarzone z określoną nazwą strony kodowej. Parametry określają procedurę obsługi błędów dla znaków, których nie można kodować i sekwencje bajtów, których nie można zdekodować.

GetEncoding(Int32)

Źródło:
Encoding.cs
Źródło:
Encoding.cs
Źródło:
Encoding.cs

Zwraca kodowanie skojarzone z określonym identyfikatorem strony kodu.

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

Parametry

codepage
Int32

Identyfikator strony kodowej preferowanego kodowania. Aby uzyskać listę możliwych wartości, zobacz Encoding.

-lub-

0 (zero), aby użyć kodowania domyślnego.

Zwraca

Kodowanie skojarzone z określoną stroną kodu.

Wyjątki

codepage wartość jest mniejsza niż zero lub większa niż 65535.

codepage nie jest obsługiwana przez podstawową platformę.

codepage nie jest obsługiwana przez podstawową platformę.

Przykłady

Poniższy przykład pobiera dwa wystąpienia tego samego kodowania (jeden według strony kodu i inny według nazwy) i sprawdza ich równość.

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

Uwagi

Program obsługi rezerwowej zależy od typu kodowania .codepage Jeśli codepage jest kodowaniem strony kodowej lub zestawu znaków dwubajtowych (DBCS), jest używana procedura obsługi rezerwowej najlepiej dopasowana. W przeciwnym razie jest używana procedura obsługi rezerwowej zamiany. Te rezerwowe procedury obsługi mogą nie być odpowiednie dla twojej aplikacji. Aby określić program obsługi rezerwowej używany przez kodowanie określone przez codepagemetodę GetEncoding(Int32, EncoderFallback, DecoderFallback) , można wywołać przeciążenie.

W .NET Framework GetEncoding metoda opiera się na podstawowej platformie do obsługi większości stron kodu. Jednak .NET Framework natywnie obsługuje niektóre kodowanie. Aby uzyskać listę stron kodu, zobacz Lista kodowań. W programie .NET Core GetEncoding metoda zwraca kodowanie natywnie obsługiwane przez platformę .NET Core. W obu implementacjach platformy .NET można wywołać GetEncodings metodę , aby uzyskać tablicę EncodingInfo obiektów zawierających informacje o wszystkich dostępnych kodowaniu.

Oprócz kodowań, które są natywnie dostępne na platformie .NET Core lub które są wewnętrznie obsługiwane w określonej wersji platformy .NET Framework, GetEncoding metoda zwraca wszelkie dodatkowe kodowania udostępniane przez zarejestrowanie EncodingProvider obiektu. Jeśli to samo kodowanie zostało zarejestrowane przez wiele EncodingProvider obiektów, ta metoda zwraca ostatni zarejestrowany.

Możesz również podać wartość 0 dla argumentu codepage . Jego dokładne zachowanie zależy od tego, czy jakiekolwiek kodowanie zostało udostępnione przez zarejestrowanie EncodingProvider obiektu:

  • Jeśli zarejestrowano co najmniej jednego dostawcę kodowania, zwraca kodowanie ostatniego zarejestrowanego dostawcy, który zdecydował się zwrócić kodowanie po GetEncoding przekazaniu codepage argumentu 0.

  • W .NET Framework, jeśli żaden dostawca kodowania nie został zarejestrowany, jeśli CodePagesEncodingProvider jest zarejestrowanym dostawcą kodowania lub jeśli żaden zarejestrowany dostawca kodowania nie obsługuje codepage wartości 0, zwraca aktywną stronę kodu systemu operacyjnego. Aby określić aktywną stronę kodu w systemach Windows, wywołaj funkcję GetACP systemu Windows z .NET Framework.

  • Jeśli na platformie .NET Core nie zarejestrowano żadnego dostawcy kodowania lub jeśli żaden zarejestrowany dostawca kodowania nie obsługuje codepage wartości 0, zwraca UTF8Encodingwartość .

Uwaga

  • Niektóre nieobsługiwane strony kodu powodują, że element ArgumentException jest zgłaszany, podczas gdy inne powodują błąd NotSupportedException. W związku z tym kod musi przechwytywać wszystkie wyjątki wskazane w sekcji Wyjątki.
  • W wersjach .NET 5 i nowszych identyfikator 65000strony kodu , który reprezentuje UTF-7, nie jest obsługiwany.

Uwaga

Strony kodu ANSI mogą być różne na różnych komputerach i mogą ulec zmianie na jednym komputerze, co prowadzi do uszkodzenia danych. Z tego powodu, jeśli aktywna strona kodu jest stroną kodową ANSI, kodowanie i dekodowanie danych przy użyciu domyślnej strony kodu zwracanej przez Encoding.GetEncoding(0) program nie jest zalecane. W przypadku najbardziej spójnych wyników należy użyć kodowania Unicode, takiego jak UTF-8 (strona kodowa 65001) lub UTF-16, zamiast określonej strony kodowej.

GetEncoding zwraca buforowane wystąpienie z ustawieniami domyślnymi. Należy użyć konstruktorów klas pochodnych, aby uzyskać wystąpienie z różnymi ustawieniami. Na przykład UTF32Encoding klasa udostępnia konstruktor, który umożliwia włączenie wykrywania błędów.

Zobacz też

Dotyczy

GetEncoding(String)

Źródło:
Encoding.cs
Źródło:
Encoding.cs
Źródło:
Encoding.cs

Zwraca kodowanie skojarzone z określoną nazwą strony kodowej.

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

Parametry

name
String

Nazwa strony kodowej preferowanego kodowania. Każda wartość zwrócona przez właściwość jest prawidłowa WebName . Aby uzyskać listę możliwych wartości, zobacz Encoding.

Zwraca

Kodowanie skojarzone z określoną stroną kodu.

Wyjątki

name nie jest prawidłową nazwą strony kodowej.

-lub-

Strona kodowa wskazana przez name program nie jest obsługiwana przez platformę podstawową.

Przykłady

Poniższy przykład pobiera dwa wystąpienia tego samego kodowania (jeden według strony kodu i inny według nazwy) i sprawdza ich równość.

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

Uwagi

Program obsługi rezerwowej zależy od typu kodowania .name Jeśli name jest kodowaniem strony kodowej lub zestawu znaków dwubajtowych (DBCS), jest używana procedura obsługi rezerwowej najlepiej dopasowana. W przeciwnym razie jest używana procedura obsługi rezerwowej zamiany. Te rezerwowe procedury obsługi mogą nie być odpowiednie dla twojej aplikacji. Aby określić program obsługi rezerwowej używany przez kodowanie określone przez namemetodę GetEncoding(String, EncoderFallback, DecoderFallback) , można wywołać przeciążenie.

W .NET Framework GetEncoding metoda opiera się na podstawowej platformie do obsługi większości stron kodu. Jednak .NET Framework natywnie obsługuje niektóre kodowanie. Aby uzyskać listę stron kodu, zobacz Lista kodowań. W programie .NET Core GetEncoding metoda zwraca kodowanie natywnie obsługiwane przez platformę .NET Core. W obu implementacjach platformy .NET można wywołać GetEncodings metodę , aby uzyskać tablicę EncodingInfo obiektów zawierających informacje o wszystkich dostępnych kodowaniu.

Oprócz kodowań, które są natywnie dostępne na platformie .NET Core lub które są wewnętrznie obsługiwane w określonej wersji platformy .NET Framework, GetEncoding metoda zwraca wszelkie dodatkowe kodowania udostępniane przez zarejestrowanie EncodingProvider obiektu. Jeśli to samo kodowanie zostało zarejestrowane przez wiele EncodingProvider obiektów, ta metoda zwraca ostatni zarejestrowany.

W programie .NET 5 i nowszych wersjach nazwa utf-7 strony kodowej nie jest obsługiwana.

Uwaga

Strony kodu ANSI mogą być różne na różnych komputerach lub można je zmienić dla jednego komputera, co prowadzi do uszkodzenia danych. W przypadku najbardziej spójnych wyników użyj formatu Unicode, takiego jak UTF-8 (strona kodowa 65001) lub UTF-16, zamiast określonej strony kodowej.

GetEncoding zwraca buforowane wystąpienie z ustawieniami domyślnymi. Należy użyć konstruktorów klas pochodnych, aby uzyskać wystąpienie z różnymi ustawieniami. Na przykład UTF32Encoding klasa udostępnia konstruktor, który umożliwia włączenie wykrywania błędów.

Zobacz też

Dotyczy

GetEncoding(Int32, EncoderFallback, DecoderFallback)

Źródło:
Encoding.cs
Źródło:
Encoding.cs
Źródło:
Encoding.cs

Zwraca kodowanie skojarzone z określonym identyfikatorem strony kodu. Parametry określają procedurę obsługi błędów dla znaków, których nie można kodować i sekwencje bajtów, których nie można zdekodować.

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

Parametry

codepage
Int32

Identyfikator strony kodowej preferowanego kodowania. Aby uzyskać listę możliwych wartości, zobacz Encoding.

-lub-

0 (zero), aby użyć kodowania domyślnego.

encoderFallback
EncoderFallback

Obiekt, który zapewnia procedurę obsługi błędów, gdy znak nie może być zakodowany przy użyciu bieżącego kodowania.

decoderFallback
DecoderFallback

Obiekt, który zapewnia procedurę obsługi błędów, gdy sekwencja bajtów nie może zostać zdekodowana przy użyciu bieżącego kodowania.

Zwraca

Kodowanie skojarzone z określoną stroną kodu.

Wyjątki

codepage wartość jest mniejsza niż zero lub większa niż 65535.

codepage nie jest obsługiwana przez podstawową platformę.

codepage nie jest obsługiwana przez podstawową platformę.

Przykłady

W poniższym przykładzie pokazano metodę 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)"
'

Uwagi

Uwaga

  • Niektóre nieobsługiwane strony kodu powodują zgłoszenie wyjątku ArgumentException , podczas gdy inne powodują NotSupportedException. W związku z tym kod musi przechwytywać wszystkie wyjątki wskazane w sekcji Wyjątki.
  • W wersjach .NET 5 i nowszych identyfikator 65000strony kodu , który reprezentuje UTF-7, nie jest obsługiwany.

W .NET Framework GetEncoding metoda opiera się na podstawowej platformie do obsługi większości stron kodu. Jednak .NET Framework natywnie obsługuje niektóre kodowanie. Aby uzyskać listę stron kodu, zobacz Lista kodowań. W programie .NET Core GetEncoding metoda zwraca kodowanie natywnie obsługiwane przez platformę .NET Core. W obu implementacjach platformy .NET można wywołać GetEncodings metodę , aby uzyskać tablicę EncodingInfo obiektów zawierających informacje o wszystkich dostępnych kodowaniu.

Oprócz kodowań, które są natywnie dostępne na platformie .NET Core lub które są wewnętrznie obsługiwane w określonej wersji platformy .NET Framework, GetEncoding metoda zwraca wszelkie dodatkowe kodowania udostępniane przez zarejestrowanie EncodingProvider obiektu. Jeśli to samo kodowanie zostało zarejestrowane przez wiele EncodingProvider obiektów, ta metoda zwraca ostatni zarejestrowany.

Możesz również podać wartość 0 dla argumentu codepage . Jego dokładne zachowanie zależy od tego, czy jakiekolwiek kodowanie zostało udostępnione przez zarejestrowanie EncodingProvider obiektu:

  • Jeśli zarejestrowano co najmniej jednego dostawcę kodowania, zwraca kodowanie ostatniego zarejestrowanego dostawcy, który zdecydował się zwrócić kodowanie po GetEncoding przekazaniu codepage argumentu 0.

  • W .NET Framework, jeśli żaden dostawca kodowania nie został zarejestrowany, jeśli CodePagesEncodingProvider jest zarejestrowanym dostawcą kodowania lub jeśli żaden zarejestrowany dostawca kodowania nie obsługuje codepage wartości 0, zwraca aktywną stronę kodu.

  • Jeśli na platformie .NET Core nie zarejestrowano żadnego dostawcy kodowania lub jeśli żaden zarejestrowany dostawca kodowania nie obsługuje codepage wartości 0, zwraca UTF8Encoding kodowanie.

Uwaga

Strony kodu ANSI mogą być różne na różnych komputerach i mogą ulec zmianie na jednym komputerze, co prowadzi do uszkodzenia danych. Z tego powodu, jeśli aktywna strona kodu jest stroną kodową ANSI, kodowanie i dekodowanie danych przy użyciu domyślnej strony kodu zwracanej przez Encoding.GetEncoding(0) program nie jest zalecane. W przypadku najbardziej spójnych wyników należy użyć formatu Unicode, takiego jak UTF-8 (strona kodowa 65001) lub UTF-16, zamiast określonej strony kodowej.

Aby uzyskać kodowanie skojarzone z aktywną stroną kodu, możesz podać wartość 0 dla argumentu codepage lub, jeśli kod jest uruchomiony na .NET Framework, pobierz wartość Encoding.Default właściwości. Aby określić bieżącą aktywną stronę kodu, wywołaj funkcję GetACP systemu Windows z .NET Framework.

GetEncoding zwraca buforowane wystąpienie z ustawieniami domyślnymi. Należy użyć konstruktorów klas pochodnych, aby uzyskać wystąpienie z różnymi ustawieniami. Na przykład UTF32Encoding klasa udostępnia konstruktor, który umożliwia włączenie wykrywania błędów.

Zobacz też

Dotyczy

GetEncoding(String, EncoderFallback, DecoderFallback)

Źródło:
Encoding.cs
Źródło:
Encoding.cs
Źródło:
Encoding.cs

Zwraca kodowanie skojarzone z określoną nazwą strony kodowej. Parametry określają procedurę obsługi błędów dla znaków, których nie można kodować i sekwencje bajtów, których nie można zdekodować.

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

Parametry

name
String

Nazwa strony kodowej preferowanego kodowania. Każda wartość zwrócona przez właściwość jest prawidłowa WebName . Możliwe wartości są wymienione w kolumnie Nazwa tabeli wyświetlanej Encoding w temacie klasy.

encoderFallback
EncoderFallback

Obiekt, który zapewnia procedurę obsługi błędów, gdy znak nie może być zakodowany przy użyciu bieżącego kodowania.

decoderFallback
DecoderFallback

Obiekt, który zapewnia procedurę obsługi błędów, gdy sekwencja bajtów nie może zostać zdekodowana przy użyciu bieżącego kodowania.

Zwraca

Kodowanie skojarzone z określoną stroną kodu.

Wyjątki

name nie jest prawidłową nazwą strony kodowej.

-lub-

Strona kodowa wskazana przez name program nie jest obsługiwana przez platformę podstawową.

Przykłady

W poniższym przykładzie pokazano metodę 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)"
'

Uwagi

W .NET Framework GetEncoding metoda opiera się na podstawowej platformie do obsługi większości stron kodu. Jednak .NET Framework natywnie obsługuje niektóre kodowanie. Aby uzyskać listę stron kodu, zobacz Lista kodowań. W programie .NET Core GetEncoding metoda zwraca kodowanie natywnie obsługiwane przez platformę .NET Core. W obu implementacjach platformy .NET można wywołać GetEncodings metodę , aby uzyskać tablicę EncodingInfo obiektów zawierających informacje o wszystkich dostępnych kodowaniu.

Oprócz kodowań, które są natywnie dostępne na platformie .NET Core lub które są wewnętrznie obsługiwane w określonej wersji platformy .NET Framework, GetEncoding metoda zwraca wszelkie dodatkowe kodowania udostępniane przez zarejestrowanie EncodingProvider obiektu. Jeśli to samo kodowanie zostało zarejestrowane przez wiele EncodingProvider obiektów, ta metoda zwraca ostatni zarejestrowany.

W programie .NET 5 i nowszych wersjach nazwa utf-7 strony kodowej nie jest obsługiwana.

Uwaga

Strony kodu ANSI mogą być różne na różnych komputerach i mogą ulec zmianie na jednym komputerze, co prowadzi do uszkodzenia danych. W przypadku najbardziej spójnych wyników należy użyć kodowania Unicode, takiego jak UTF-8 (strona kodowa 65001) lub UTF-16, zamiast określonej strony kodowej.

GetEncoding zwraca buforowane wystąpienie z ustawieniami domyślnymi. Należy użyć konstruktorów klas pochodnych, aby uzyskać wystąpienie z różnymi ustawieniami. Na przykład UTF32Encoding klasa udostępnia konstruktor, który umożliwia włączenie wykrywania błędów.

Zobacz też

Dotyczy