Encoding.GetEncoding メソッド

定義

指定したコード ページのエンコーディングを返します。

オーバーロード

GetEncoding(Int32)

指定したコード ページ ID に関連付けられたエンコーディングを返します。

GetEncoding(String)

指定したコード ページ名に関連付けられたエンコーディングを返します。

GetEncoding(Int32, EncoderFallback, DecoderFallback)

指定したコード ページ ID に関連付けられたエンコーディングを返します。 パラメーターには、エンコードできない文字とデコードできないバイト シーケンスのためのエラー ハンドラーを指定します。

GetEncoding(String, EncoderFallback, DecoderFallback)

指定したコード ページ名に関連付けられたエンコーディングを返します。 パラメーターには、エンコードできない文字とデコードできないバイト シーケンスのためのエラー ハンドラーを指定します。

GetEncoding(Int32)

Source:
Encoding.cs
Source:
Encoding.cs
Source:
Encoding.cs

指定したコード ページ ID に関連付けられたエンコーディングを返します。

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
Int32

使用するエンコーディングのコード ページ ID。 有効な値の一覧については、「Encoding」を参照してください。

- または -

既定のエンコーディングを使用する場合は 0。

戻り値

指定したコード ページに関連付けられたエンコーディング。

例外

codepage が 0 未満か、65535 を超えています。

codepage は、基になるプラットフォームでサポートされていません。

codepage は、基になるプラットフォームでサポートされていません。

次の例では、同じエンコードの2つのインスタンスを取得します (コードページごとに、もう1つは名前別)。

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がコードページまたは2バイト文字セット (DBCS) エンコーディングの場合は、最適フォールバックハンドラーが使用されます。 それ以外の場合は、置換フォールバックハンドラーが使用されます。 これらのフォールバックハンドラーは、アプリに適していない場合があります。 によって指定されたエンコーディングによって使用されるフォールバックハンドラーを指定するために codepage 、オーバーロードを呼び出すことができ GetEncoding(Int32, EncoderFallback, DecoderFallback) ます。

.NET Framework では、 GetEncoding メソッドは、ほとんどのコードページをサポートするために、基になるプラットフォームに依存します。 ただし、.NET Framework は、いくつかのエンコーディングをネイティブでサポートしています。 コードページの一覧については、「エンコーディングの一覧」を参照してください。 .NET Core では、 GetEncoding メソッドは .Net core でネイティブにサポートされているエンコーディングを返します。 どちらの .NET 実装でも、メソッドを呼び出して、 GetEncodingsEncodingInfo 使用可能なすべてのエンコーディングに関する情報を含むオブジェクトの配列を取得できます。

.NET Core でネイティブに提供されている、または特定のプラットフォームバージョンの .NET Framework で本質的にサポートされているエンコーディングに加えて、メソッドは、 GetEncoding オブジェクトの登録によって使用可能になる追加のエンコーディングを返し EncodingProvider ます。 同じエンコーディングが複数のオブジェクトによって登録されている場合 EncodingProvider 、このメソッドは最後に登録されたものを返します。

引数に値0を指定することもでき codepage ます。 その正確な動作は、オブジェクトを登録することによって、エンコードが使用可能になっているかどうかによって異なり EncodingProvider ます。

  • 1つまたは複数のエンコーディングプロバイダーが登録されている場合は、メソッドに0の引数が渡されたときにエンコーディングを返すことを選択した最後に登録されたプロバイダーのエンコーディングを返し GetEncodingcodepage ます。

  • .NET Framework で、エンコーディングプロバイダーが登録されていない場合、が登録済みのエンコーディングプロバイダーである場合、または登録されているエンコーディングプロバイダーが CodePagesEncodingProvider 0 の値を処理しない場合は、 codepage オペレーティングシステムのアクティブなコードページが返されます。 Windows システムでアクティブなコード ページを確認するには、.NET Frameworkから Windows GetACP 関数を呼び出します。

  • .NET Core では、エンコーディングプロバイダーが登録されていない場合、または登録済みのエンコーディングプロバイダーが0の値を処理しない場合は codepage 、が返され UTF8Encoding ます。

Note

  • サポートされていないコードページが原因でが ArgumentException スローされることがあり NotSupportedException ます。 そのため、コードでは、例外セクションに示されているすべての例外をキャッチする必要があります。
  • .NET 5 以降のバージョンでは、UTF-7 を表すコード ページ識別子 65000はサポートされていません。

Note

ANSI コードページは、コンピューターによって異なる場合があり、1台のコンピューターで変更できるため、データが破損する可能性があります。 このため、アクティブなコードページが ANSI コードページである場合、によって返される既定のコードページを使用してデータをエンコードおよびデコードする Encoding.GetEncoding(0) ことはお勧めできません。 最も一貫性のある結果を得るには、特定のコードページではなく、UTF-8 (コードページ 65001) や UTF-16 などの Unicode エンコードを使用する必要があります。

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

パラメーター

name
String

使用するエンコーディングのコード ページ名。 WebName プロパティが返す値はすべて有効です。 有効な値の一覧については、「Encoding」を参照してください。

戻り値

指定したコード ページに関連付けられたエンコード。

例外

name が有効なコード ページ名ではありません。

- または -

name が示すコード ページは基になるプラットフォームでサポートされていません。

次の例では、同じエンコードの2つのインスタンスを取得します (コードページごとに、もう1つは名前別)。

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がコードページまたは2バイト文字セット (DBCS) エンコーディングの場合は、最適フォールバックハンドラーが使用されます。 それ以外の場合は、置換フォールバックハンドラーが使用されます。 これらのフォールバックハンドラーは、アプリに適していない場合があります。 によって指定されたエンコーディングによって使用されるフォールバックハンドラーを指定するために name 、オーバーロードを呼び出すことができ GetEncoding(String, EncoderFallback, DecoderFallback) ます。

.NET Framework では、 GetEncoding メソッドは、ほとんどのコードページをサポートするために、基になるプラットフォームに依存します。 ただし、.NET Framework は、いくつかのエンコーディングをネイティブでサポートしています。 コードページの一覧については、「エンコーディングの一覧」を参照してください。 .NET Core では、 GetEncoding メソッドは .Net core でネイティブにサポートされているエンコーディングを返します。 どちらの .NET 実装でも、メソッドを呼び出して、 GetEncodingsEncodingInfo 使用可能なすべてのエンコーディングに関する情報を含むオブジェクトの配列を取得できます。

.NET Core でネイティブに提供されている、または特定のプラットフォームバージョンの .NET Framework で本質的にサポートされているエンコーディングに加えて、メソッドは、 GetEncoding オブジェクトの登録によって使用可能になる追加のエンコーディングを返し EncodingProvider ます。 同じエンコーディングが複数のオブジェクトによって登録されている場合 EncodingProvider 、このメソッドは最後に登録されたものを返します。

.NET 5 以降のバージョンでは、コード ページ名 utf-7 はサポートされていません。

Note

ANSI コードページは、コンピューターによって異なる場合もあれば、1台のコンピューターでは変更でき、データの破損を招く場合もあります。 最も一貫性のある結果を得るには、特定のコードページではなく、UTF-8 (コードページ 65001) や UTF-16 などの Unicode を使用します。

GetEncoding既定の設定でキャッシュされたインスタンスを返します。 異なる設定のインスタンスを取得するには、派生クラスのコンストラクターを使用する必要があります。 たとえば、クラスには、 UTF32Encoding エラー検出を可能にするコンストラクターが用意されています。

こちらもご覧ください

適用対象

GetEncoding(Int32, EncoderFallback, DecoderFallback)

Source:
Encoding.cs
Source:
Encoding.cs
Source:
Encoding.cs

指定したコード ページ ID に関連付けられたエンコーディングを返します。 パラメーターには、エンコードできない文字とデコードできないバイト シーケンスのためのエラー ハンドラーを指定します。

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

パラメーター

codepage
Int32

使用するエンコーディングのコード ページ ID。 有効な値の一覧については、「Encoding」を参照してください。

- または -

既定のエンコーディングを使用する場合は 0。

encoderFallback
EncoderFallback

現在のエンコーディングで文字をエンコードできない場合にエラー処理プロシージャを提供するオブジェクト。

decoderFallback
DecoderFallback

現在のエンコーディングでバイト シーケンスをデコードできない場合にエラー処理プロシージャを提供するオブジェクト。

戻り値

指定したコード ページに関連付けられたエンコーディング。

例外

codepage が 0 未満か、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)"
'

注釈

Note

  • サポートされていないコードページが原因で例外が ArgumentException スローされる場合があり NotSupportedException ます。 そのため、コードでは、例外セクションに示されているすべての例外をキャッチする必要があります。
  • .NET 5 以降のバージョンでは、UTF-7 を表すコード ページ識別子 65000はサポートされていません。

.NET Framework では、 GetEncoding メソッドは、ほとんどのコードページをサポートするために、基になるプラットフォームに依存します。 ただし、.NET Framework は、いくつかのエンコーディングをネイティブでサポートしています。 コードページの一覧については、「エンコーディングの一覧」を参照してください。 .NET Core では、 GetEncoding メソッドは .Net core でネイティブにサポートされているエンコーディングを返します。 どちらの .NET 実装でも、メソッドを呼び出して、 GetEncodingsEncodingInfo 使用可能なすべてのエンコーディングに関する情報を含むオブジェクトの配列を取得できます。

.NET Core でネイティブに提供されている、または特定のプラットフォームバージョンの .NET Framework で本質的にサポートされているエンコーディングに加えて、メソッドは、 GetEncoding オブジェクトの登録によって使用可能になる追加のエンコーディングを返し EncodingProvider ます。 同じエンコーディングが複数のオブジェクトによって登録されている場合 EncodingProvider 、このメソッドは最後に登録されたものを返します。

引数に値0を指定することもでき codepage ます。 その正確な動作は、オブジェクトを登録することによって、エンコードが使用可能になっているかどうかによって異なり EncodingProvider ます。

  • 1つまたは複数のエンコーディングプロバイダーが登録されている場合は、メソッドに0の引数が渡されたときにエンコーディングを返すことを選択した最後に登録されたプロバイダーのエンコーディングを返し GetEncodingcodepage ます。

  • .NET Framework で、エンコーディングプロバイダーが登録されていない場合、が登録済みのエンコーディングプロバイダーである場合、または登録されている CodePagesEncodingProvider エンコーディングプロバイダーが0の値を処理しない場合は、 codepage アクティブなコードページが返されます。

  • .NET Core では、エンコーディングプロバイダーが登録されていない場合、または登録済みのエンコーディングプロバイダーが0の値を処理しない場合 codepage 、エンコーディングが返され UTF8Encoding ます。

Note

ANSI コードページは、コンピューターによって異なる場合があり、1台のコンピューターで変更できるため、データが破損する可能性があります。 このため、アクティブなコードページが ANSI コードページである場合、によって返される既定のコードページを使用してデータをエンコードおよびデコードする Encoding.GetEncoding(0) ことはお勧めできません。 一貫性のある結果を得るには、特定のコードページではなく、UTF-8 (コードページ 65001) や UTF-16 などの Unicode を使用する必要があります。

アクティブなコード ページに関連付けられているエンコードを取得するには、引数に値 0 をcodepage指定するか、コードが .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

パラメーター

name
String

使用するエンコーディングのコード ページ名。 WebName プロパティが返す値はすべて有効です。 使用可能な値は、Encoding クラスのトピックに記載されている表の、名前の列にリストされています。

encoderFallback
EncoderFallback

現在のエンコーディングで文字をエンコードできない場合にエラー処理プロシージャを提供するオブジェクト。

decoderFallback
DecoderFallback

現在のエンコーディングでバイト シーケンスをデコードできない場合にエラー処理プロシージャを提供するオブジェクト。

戻り値

指定したコード ページに関連付けられたエンコーディング。

例外

name が有効なコード ページ名ではありません。

- または -

name が示すコード ページは基になるプラットフォームでサポートされていません。

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 実装でも、メソッドを呼び出して、 GetEncodingsEncodingInfo 使用可能なすべてのエンコーディングに関する情報を含むオブジェクトの配列を取得できます。

.NET Core でネイティブに提供されている、または特定のプラットフォームバージョンの .NET Framework で本質的にサポートされているエンコーディングに加えて、メソッドは、 GetEncoding オブジェクトの登録によって使用可能になる追加のエンコーディングを返し EncodingProvider ます。 同じエンコーディングが複数のオブジェクトによって登録されている場合 EncodingProvider 、このメソッドは最後に登録されたものを返します。

.NET 5 以降のバージョンでは、コード ページ名 utf-7 はサポートされていません。

Note

ANSI コードページは、コンピューターによって異なる場合があり、1台のコンピューターで変更できるため、データが破損する可能性があります。 最も一貫性のある結果を得るには、特定のコードページではなく、UTF-8 (コードページ 65001) や UTF-16 などの Unicode エンコードを使用する必要があります。

GetEncoding既定の設定でキャッシュされたインスタンスを返します。 異なる設定のインスタンスを取得するには、派生クラスのコンストラクターを使用する必要があります。 たとえば、クラスには、 UTF32Encoding エラー検出を可能にするコンストラクターが用意されています。

こちらもご覧ください

適用対象