C# Encoding GetEncoding(String, EncoderFallback, DecoderFallback)
Description
Encoding GetEncoding(String, EncoderFallback, DecoderFallback)
Returns the encoding associated with the specified code page name.
Parameters specify an error handler for characters that cannot be encoded
and byte sequences that cannot be decoded.
Syntax
Encoding.GetEncoding(String, EncoderFallback, DecoderFallback)
has the following syntax.
public static Encoding GetEncoding(
string name,// ww w . j a va 2 s. c o m
EncoderFallback encoderFallback,
DecoderFallback decoderFallback
)
Parameters
Encoding.GetEncoding(String, EncoderFallback, DecoderFallback)
has the following parameters.
name
- The code page name of the preferred encoding. Any value returned by the WebName property is valid. Possible values are listed in the Name column of the table that appears in the Encoding class topic.encoderFallback
- An object that provides an error-handling procedure when a character cannot be encoded with the current encoding.decoderFallback
- An object that provides an error-handling procedure when a byte sequence cannot be decoded with the current encoding.
Returns
Encoding.GetEncoding(String, EncoderFallback, DecoderFallback)
method returns The encoding that is associated with the specified code page.
Example
using System;/*from w w w . ja va 2 s . c o m*/
using System.Text;
class Sample
{
public static void Main()
{
Encoding ae = Encoding.GetEncoding(
"us-ascii",
new EncoderReplacementFallback("(unknown)"),
new DecoderReplacementFallback("(error)"));
string inputString = "\u00abX\u00bb";
string decodedString;
string twoNewLines = "\n\n";
byte[] encodedBytes = new byte[ae.GetByteCount(inputString)];
int numberOfEncodedBytes = 0;
int ix = 0;
foreach (char c in inputString.ToCharArray()) {
Console.Write("0x{0:X2} ", (int)c);
}
Console.Write(twoNewLines);
numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length,
encodedBytes, 0);
Console.WriteLine(numberOfEncodedBytes);
ix = 0;
decodedString = ae.GetString(encodedBytes);
Console.WriteLine("Input string: \"{0}\"", inputString);
Console.WriteLine("Decoded string:\"{0}\"", decodedString);
}
}
The code above generates the following result.