System.Text.Encoding Class
Assembly: System.Runtime.dll
Summary
Represents a character encoding. Encoding is a mechanism that assigns a unique number (a code point) to every character in a character set. Different encodings use different mappings.
The Encoding class is an abstract base class that provides access to a variety of encodings, including ASCII, UTF-7, UTF-8, UTF-32, and Unicode (UTF-16).
Properties
-
ASCII
public static System.Text.ASCIIEncoding ASCII { get; }Gets an instance of the ASCII encoding.
-
UTF7
public static System.Text.UTF7Encoding UTF7 { get; }Gets an instance of the UTF-7 encoding.
-
UTF8
public static System.Text.UTF8Encoding UTF8 { get; }Gets an instance of the UTF-8 encoding.
-
UTF32
public static System.Text.UTF32Encoding UTF32 { get; }Gets an instance of the UTF-32 encoding.
-
Unicode
public static System.Text.UnicodeEncoding Unicode { get; }Gets an instance of the UTF-16 (little-endian) encoding.
-
Default
public static System.Text.Encoding Default { get; }Gets the default encoding for the current computer.
Methods
-
GetByteCount(char[])
public int GetByteCount(char[] chars)Calculates the number of bytes produced by encoding a character array into the current encoding.
-
GetBytes(char[])
public byte[] GetBytes(char[] chars)Encodes all the characters in the character array into a sequence of bytes.
-
GetString(byte[])
public string GetString(byte[] bytes)Decodes all the bytes in the byte array into a string.
-
GetChars(byte[])
public char[] GetChars(byte[] bytes)Decodes all the bytes in the byte array into a sequence of characters.
-
GetEncoding(int)
public static System.Text.Encoding GetEncoding(int codepage)Returns an instance of a specified encoding.
-
GetEncoding(string)
public static System.Text.Encoding GetEncoding(string name)Returns an instance of a specified encoding.
Remarks
The Encoding class is fundamental for handling text data that may originate from or be destined for various external sources, such as files, network streams, or databases, each potentially using a different character encoding.
When you need to convert strings to byte arrays (encoding) or byte arrays to strings (decoding), the Encoding class provides the necessary tools. For example, to convert a C# string to its UTF-8 byte representation, you would use:
Encoding utf8 = Encoding.UTF8;
byte[] bytes = utf8.GetBytes(chars);
Conversely, to convert a byte array back to a string using UTF-8:
// decodedString will be "Hello"