See Also: ASCIIEncoding Members
Encoding is the process of transforming a set of Unicode characters into a sequence of bytes. Decoding is the process of transforming a sequence of encoded bytes into a set of Unicode characters.
System.Text.ASCIIEncoding corresponds to the Windows code page 20127. Because ASCII is a 7-bit encoding, ASCII characters are limited to the lowest 128 Unicode characters, from U+0000 to U+007F. If you use the default encoder returned by the Encoding.ASCII property or the ASCIIEncoding.#ctor constructor, characters outside that range are replaced with a question mark (?) before the encoding operation is performed. Because the System.Text.ASCIIEncoding class supports only a limited character set, the System.Text.UTF8Encoding, System.Text.UnicodeEncoding, and System.Text.UTF32Encoding classes are better suited for globalized applications. The following considerations can help you to decide whether to use System.Text.ASCIIEncoding:
Some protocols require ASCII or a subset of ASCII. In these cases ASCII encoding is appropriate.
If an 8-bit encoding is expected, then ASCII probably isn't the correct choice. Instead, consider using UTF8 instead of ASCII. For the characters U+0000 through U+007F, the results are identical, but all Unicode characters are representable in UTF-8, which avoids data loss.
System.Text.ASCIIEncoding does not provide error detection. For security reasons, you should use System.Text.UTF8Encoding, System.Text.UnicodeEncoding, or System.Text.UTF32Encoding and enable error detection.
The ASCIIEncoding.GetByteCount(Char, int, int) method determines how many bytes result in encoding a set of Unicode characters, and the ASCIIEncoding.GetBytes(string, int, int, Byte, int) method performs the actual encoding.
Likewise, the ASCIIEncoding.GetCharCount(Byte, int, int) method determines how many characters result in decoding a sequence of bytes, and the ASCIIEncoding.GetChars(Byte, int, int, Char, int) and ASCIIEncoding.GetString(Byte, int, int) methods perform the actual decoding.
Note that the default System.Text.ASCIIEncoding constructor by itself might not have the appropriate behavior for your application. You might want to consider setting the Encoding.EncoderFallback or Encoding.DecoderFallback property to System.Text.EncoderExceptionFallback or System.Text.DecoderExceptionFallback to prevent sequences with the 8th bit set. Custom behavior might also be appropriate for these cases.