Export (0) Print
Expand All

Encoding.GetEncoding Method (Int32, EncoderFallback, DecoderFallback)

Returns the encoding associated with the specified code page identifier. Parameters specify an error handler for characters that cannot be encoded and byte sequences that cannot be decoded.

Namespace:  System.Text
Assemblies:   System.Text.Encoding (in System.Text.Encoding.dll)
  mscorlib (in mscorlib.dll)

'Declaration
Public Shared Function GetEncoding ( _
	codepage As Integer, _
	encoderFallback As EncoderFallback, _
	decoderFallback As DecoderFallback _
) As Encoding

Parameters

codepage
Type: System.Int32

The code page identifier of the preferred encoding. Possible values are listed in the Code Page column of the table that appears in the Encoding class topic.

-or-

0 (zero), to use the default encoding.

encoderFallback
Type: System.Text.EncoderFallback

An object that provides an error-handling procedure when a character cannot be encoded with the current encoding.

decoderFallback
Type: System.Text.DecoderFallback

An object that provides an error-handling procedure when a byte sequence cannot be decoded with the current encoding.

Return Value

Type: System.Text.Encoding
The encoding that is associated with the specified code page.

ExceptionCondition
ArgumentOutOfRangeException

codepage is less than zero or greater than 65535.

ArgumentException

codepage is not supported by the underlying platform.

NotSupportedException

codepage is not supported by the underlying platform.

NoteNote

Some unsupported code pages cause the exception ArgumentException to be thrown, whereas others cause NotSupportedException. Therefore, your code must catch all exceptions indicated in the Exceptions section.

The GetEncoding method relies on the underlying platform to support most code pages. However, the .NET Framework natively supports some encodings.

In addition to the encodings that are intrinsically supported on a specific platform version of the .NET Framework, the GetEncoding(Int32, EncoderFallback, DecoderFallback) method returns any additional encodings that are made available by registering an EncodingProvider object.

NoteNote

The ANSI code pages can be different on different computers, or can be changed for a single computer, leading to data corruption. For this reason, encoding and decoding data using the default code page returned by Encoding.GetEncoding(0) is not recommended. For the most consistent results, you should use Unicode, such as UTF-8 (code page 65001) or UTF-16, instead of a specific code page.

For a list of code pages, see the Encoding class topic. You can call the GetEncodings method in the full .NET Framework on the Windows desktop to get a list of all encodings.

To get the encoding associated with the default ANSI code page in the operating system's regional and language settings, you can either supply a value of 0 for the codepage argument or, if your code is running on the full .NET Framework on the Windows desktop, retrieve the value of the Encoding.Default property. To determine the default code pages used on the system, use the Windows GetSystemDefaultLangID function. To determine the current ANSI code page, call the Windows GetACP function from the full .NET Framework on the Windows desktop.

GetEncoding returns a cached instance with default settings. You should use the constructors of derived classes to get an instance with different settings. For example, the UTF32Encoding class provides a constructor that lets you enable error detection.

The following example demonstrates the Encoding.GetEncoding(String, EncoderFallback, DecoderFallback) method.

' This example demonstrates the EncoderReplacementFallback class. 
Imports System
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 

        ' --------------------------------------------------------------------------
        Console.Clear()

        ' 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 'Main
End Class 'Sample

'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

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Show:
© 2015 Microsoft