Encoding.GetEncoding 메서드

정의

지정한 코드 페이지에 대한 인코딩을 반환합니다.

오버로드

GetEncoding(Int32)

지정한 코드 페이지 식별자와 관련된 인코딩을 반환합니다.

GetEncoding(String)

지정한 코드 페이지 이름과 관련된 인코딩을 반환합니다.

GetEncoding(Int32, EncoderFallback, DecoderFallback)

지정한 코드 페이지 식별자와 관련된 인코딩을 반환합니다. 매개 변수는 인코딩할 수 없는 문자 및 디코딩할 수 없는 바이트 시퀀스에 대한 오류 처리기를 지정합니다.

GetEncoding(String, EncoderFallback, DecoderFallback)

지정한 코드 페이지 이름과 관련된 인코딩을 반환합니다. 매개 변수는 인코딩할 수 없는 문자 및 디코딩할 수 없는 바이트 시퀀스에 대한 오류 처리기를 지정합니다.

GetEncoding(Int32)

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

지정한 코드 페이지 식별자와 관련된 인코딩을 반환합니다.

public:
 static System::Text::Encoding ^ GetEncoding(int codepage);
public static System.Text.Encoding GetEncoding (int codepage);
static member GetEncoding : int -> System.Text.Encoding
Public Shared Function GetEncoding (codepage As Integer) As Encoding

매개 변수

codepage
Int32

기본 설정 인코딩의 코드 페이지 식별자입니다. 사용 가능한 값 목록을 보려면 Encoding을 참조하십시오.

또는

기본 인코딩을 사용하려면 0을 사용합니다.

반환

지정한 코드 페이지와 관련된 인코딩입니다.

예외

codepage가 0보다 작거나 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

설명

대체 (fallback) 처리기는의 인코딩 유형에 따라 달라 집니다 codepage . codepage이 코드 페이지 또는 DBCS (더블 바이트 문자 집합) 인코딩이 면 최적 대체 (fallback) 처리기가 사용 됩니다. 그렇지 않으면 대체 대체 (fallback) 처리기가 사용 됩니다. 이러한 대체 (fallback) 처리기는 앱에 적합 하지 않을 수 있습니다. 로 지정 된 인코딩에 사용 되는 대체 (fallback) 처리기를 지정 하려면 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 .

  • 하나 이상의 인코딩 공급자가 등록 된 경우 GetEncoding 메서드에 codepage 0의 인수가 전달 되 면 인코딩을 반환 하도록 선택한 마지막으로 등록 된 공급자의 인코딩을 반환 합니다.

  • .NET Framework에서 인코딩 공급자가 등록 되지 않은 경우, CodePagesEncodingProvider 가 등록 된 인코딩 공급자 이거나 등록 된 인코딩 공급자가 0의 값을 처리 하지 않는 경우 codepage 운영 체제의 활성 코드 페이지를 반환 합니다. Windows 시스템의 활성 코드 페이지를 확인하려면 .NET Framework Windows GetACP 함수를 호출합니다.

  • .NET Core에서 인코딩 공급자가 등록 되지 않았거나 등록 된 인코딩 공급자가 0 값을 처리 하지 않는 경우를 codepage 반환 UTF8Encoding 합니다.

참고

  • 일부 지원 되지 않는 코드 페이지는을 ArgumentException throw 하는 반면 다른 일부는를 발생 시킵니다 NotSupportedException . 따라서 코드는 예외 섹션에 표시 된 모든 예외를 catch 해야 합니다.
  • .NET 5 이상 버전에서는 UTF-7을 나타내는 코드 페이지 식별자 65000가 지원되지 않습니다.

참고

ANSI 코드 페이지는 컴퓨터 마다 다를 수 있으며, 단일 컴퓨터에서 변경 될 수 있으며 데이터가 손상 될 수 있습니다. 이러한 이유로 활성 코드 페이지가 ANSI 코드 페이지인 경우에서 반환 된 기본 코드 페이지를 사용 하 여 데이터를 인코딩 및 디코딩하 Encoding.GetEncoding(0) 는 것이 좋습니다. 가장 일관 된 결과를 위해 특정 코드 페이지 대신 u t f-8 (코드 페이지 65001) 또는 u t f-16과 같은 유니코드 인코딩을 사용 해야 합니다.

GetEncoding기본 설정을 사용 하 여 캐시 된 인스턴스를 반환 합니다. 파생 클래스의 생성자를 사용 하 여 다른 설정으로 인스턴스를 가져와야 합니다. 예를 들어 UTF32Encoding 클래스는 오류 검색을 사용할 수 있도록 하는 생성자를 제공 합니다.

추가 정보

적용 대상

GetEncoding(String)

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

지정한 코드 페이지 이름과 관련된 인코딩을 반환합니다.

public:
 static System::Text::Encoding ^ GetEncoding(System::String ^ name);
public static System.Text.Encoding GetEncoding (string name);
static member GetEncoding : string -> System.Text.Encoding
Public Shared Function GetEncoding (name As String) As Encoding

매개 변수

name
String

기본 설정 인코딩의 코드 페이지 이름입니다. WebName 속성에서 반환된 값이 유효합니다. 사용 가능한 값 목록을 보려면 Encoding을 참조하십시오.

반환

지정한 코드 페이지와 관련된 인코딩입니다.

예외

name이 올바른 코드 페이지 이름이 아닌 경우

또는

name으로 표시된 코드 페이지가 내부 플랫폼에서 지원되지 않는 경우

예제

다음 예제에서는 동일한 인코딩의 두 인스턴스 (코드 페이지 별로 한 개, 다른 이름으로 다른 인스턴스)를 가져오고 같은지 확인 합니다.

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

설명

대체 (fallback) 처리기는의 인코딩 유형에 따라 달라 집니다 name . name이 코드 페이지 또는 DBCS (더블 바이트 문자 집합) 인코딩이 면 최적 대체 (fallback) 처리기가 사용 됩니다. 그렇지 않으면 대체 대체 (fallback) 처리기가 사용 됩니다. 이러한 대체 (fallback) 처리기는 앱에 적합 하지 않을 수 있습니다. 로 지정 된 인코딩에 사용 되는 대체 (fallback) 처리기를 지정 하려면 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 지원되지 않습니다.

참고

ANSI 코드 페이지는 컴퓨터 마다 다를 수 있으며, 단일 컴퓨터에 대해 변경 하 여 데이터 손상을 줄 수 있습니다. 가장 일관 된 결과를 위해 특정 코드 페이지 대신 u t f-8 (코드 페이지 65001) 또는 u t f-16과 같은 유니코드를 사용 합니다.

GetEncoding기본 설정을 사용 하 여 캐시 된 인스턴스를 반환 합니다. 파생 클래스의 생성자를 사용 하 여 다른 설정으로 인스턴스를 가져와야 합니다. 예를 들어 UTF32Encoding 클래스는 오류 검색을 사용할 수 있도록 하는 생성자를 제공 합니다.

추가 정보

적용 대상

GetEncoding(Int32, EncoderFallback, DecoderFallback)

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

지정한 코드 페이지 식별자와 관련된 인코딩을 반환합니다. 매개 변수는 인코딩할 수 없는 문자 및 디코딩할 수 없는 바이트 시퀀스에 대한 오류 처리기를 지정합니다.

public:
 static System::Text::Encoding ^ GetEncoding(int codepage, System::Text::EncoderFallback ^ encoderFallback, System::Text::DecoderFallback ^ decoderFallback);
public static System.Text.Encoding GetEncoding (int codepage, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback);
static member GetEncoding : int * System.Text.EncoderFallback * System.Text.DecoderFallback -> System.Text.Encoding
Public Shared Function GetEncoding (codepage As Integer, encoderFallback As EncoderFallback, decoderFallback As DecoderFallback) As Encoding

매개 변수

codepage
Int32

기본 설정 인코딩의 코드 페이지 식별자입니다. 사용 가능한 값 목록을 보려면 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)"
'

설명

참고

  • 일부 지원 되지 않는 코드 페이지에서 예외가 throw 되는 반면 다른 일부 코드 페이지에서는 예외가 발생 ArgumentExceptionNotSupportedException 합니다. 따라서 코드는 예외 섹션에 표시 된 모든 예외를 catch 해야 합니다.
  • .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 .

  • 하나 이상의 인코딩 공급자가 등록 된 경우 GetEncoding 메서드에 codepage 0의 인수가 전달 되 면 인코딩을 반환 하도록 선택한 마지막으로 등록 된 공급자의 인코딩을 반환 합니다.

  • .NET Framework에서 인코딩 공급자가 등록 되지 않은 경우, CodePagesEncodingProvider 가 등록 된 인코딩 공급자 이거나 등록 된 인코딩 공급자가 0의 값을 처리 하지 않는 경우 codepage 활성 코드 페이지를 반환 합니다.

  • .NET Core에서 인코딩 공급자가 등록 되지 않았거나 등록 된 인코딩 공급자가 0 값을 처리 하지 않는 경우 codepage 인코딩을 반환 합니다 UTF8Encoding .

참고

ANSI 코드 페이지는 컴퓨터 마다 다를 수 있으며, 단일 컴퓨터에서 변경 될 수 있으며 데이터가 손상 될 수 있습니다. 이러한 이유로 활성 코드 페이지가 ANSI 코드 페이지인 경우에서 반환 된 기본 코드 페이지를 사용 하 여 데이터를 인코딩 및 디코딩하 Encoding.GetEncoding(0) 는 것이 좋습니다. 가장 일관 된 결과를 위해 특정 코드 페이지 대신 u t f-8 (코드 페이지 65001) 또는 u t f-16과 같은 유니코드를 사용 해야 합니다.

활성 코드 페이지와 연결된 인코딩을 얻으려면 인수에 대해 codepage 0 값을 제공하거나 코드가 .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 지원되지 않습니다.

참고

ANSI 코드 페이지는 컴퓨터 마다 다를 수 있으며, 단일 컴퓨터에서 변경 될 수 있으며 데이터가 손상 될 수 있습니다. 가장 일관 된 결과를 위해 특정 코드 페이지 대신 u t f-8 (코드 페이지 65001) 또는 u t f-16과 같은 유니코드 인코딩을 사용 해야 합니다.

GetEncoding기본 설정을 사용 하 여 캐시 된 인스턴스를 반환 합니다. 파생 클래스의 생성자를 사용 하 여 다른 설정으로 인스턴스를 가져와야 합니다. 예를 들어 UTF32Encoding 클래스는 오류 검색을 사용할 수 있도록 하는 생성자를 제공 합니다.

추가 정보

적용 대상