Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
ASCIIEncoding Class
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
ASCIIEncoding Class

Represents an ASCII character encoding of Unicode characters.

Namespace:  System.Text
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Class ASCIIEncoding _
    Inherits Encoding
Visual Basic (Usage)
Dim instance As ASCIIEncoding
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public class ASCIIEncoding : Encoding
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class ASCIIEncoding : public Encoding
JScript
public class ASCIIEncoding extends Encoding

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.

ASCIIEncoding corresponds to the Windows code page 20127. ASCII characters are limited to the lowest 128 Unicode characters, from U+0000 to U+007F. For more information about the encodings supported by System.Text, see Understanding Encodings and Using Unicode Encoding.

Caution noteCaution:

ASCIIEncoding does not provide error detection. For security reasons, your application is recommended to use UTF8Encoding, UnicodeEncoding, or UTF32Encoding and enable error detection.

NoteNote:

Since ASCIIEncoding supports only the Unicode character values between U+0000 and U+007F, UTF8Encoding, UnicodeEncoding, and UTF32Encoding are better suited for globalized applications.

The GetByteCount method determines how many bytes result in encoding a set of Unicode characters, and the GetBytes method performs the actual encoding.

Likewise, the GetCharCount method determines how many characters result in decoding a sequence of bytes, and the GetChars and GetString methods perform the actual decoding.

When selecting the ASCII encoding for your applications, consider the following:

  • The ASCII encoding is usually appropriate for protocols that require ASCII.

  • If your application requires 8-bit encoding, the UTF-8 encoding is recommended over the ASCII encoding. For the characters 0-7F, the results are identical, but use of UTF-8 avoids data loss by allowing representation of all Unicode characters that are representable. Note that the ASCII encoding has an 8th bit ambiguity that can allow malicious use, but the UTF-8 encoding removes ambiguity about the 8th bit.

  • Previous versions of .NET Framework allowed spoofing by merely ignoring the 8th bit. The current version has been changed so that non-ASCII code points fall back during the decoding of bytes.

Note that the default ASCIIEncoding constructor by itself might not have the appropriate behavior for your application. You might want to consider having your application set EncoderFallback or DecoderFallback to EncoderExceptionFallback or DecoderExceptionFallback to prevent sequences with the 8th bit set. Custom behavior might also be appropriate for these cases.

The following example demonstrates how to encode Unicode characters into ASCII. Notice the loss of data that occurs when your application uses ASCIIEncoding to encode Unicode characters outside of the ASCII range.

Visual Basic
Imports System
Imports System.Text
Imports Microsoft.VisualBasic.Strings

Class ASCIIEncodingExample
    Public Shared Sub Main()
        ' The encoding.
        Dim ascii As New ASCIIEncoding()

        ' A Unicode string with two characters outside the ASCII code range.
        Dim unicodeString As String = _
            "This Unicode string contains two characters " & _
            "with codes outside the ASCII code range, " & _
            "Pi (" & ChrW(928) & ") and Sigma (" & ChrW(931) & ")."
        Console.WriteLine("Original string:")
        Console.WriteLine(unicodeString)

        ' Save positions of the special characters for later reference.
        Dim indexOfPi As Integer = unicodeString.IndexOf(ChrW(928))
        Dim indexOfSigma As Integer = unicodeString.IndexOf(ChrW(931))

        ' Encode string.
        Dim encodedBytes As Byte() = ascii.GetBytes(unicodeString)
        Console.WriteLine()
        Console.WriteLine("Encoded bytes:")
        Dim b As Byte
        For Each b In encodedBytes
            Console.Write("[{0}]", b)
        Next b
        Console.WriteLine()

        ' Notice that the special characters have been replaced with
        ' the value 63, which is the ASCII character code for '?'.
        Console.WriteLine()
        Console.WriteLine( _
            "Value at position of Pi character: {0}", _
            encodedBytes(indexOfPi) _
        )
        Console.WriteLine( _
            "Value at position of Sigma character: {0}", _
            encodedBytes(indexOfSigma) _
        )

        ' Decode bytes back to string.
        ' Notice missing Pi and Sigma characters.
        Dim decodedString As String = ascii.GetString(encodedBytes)
        Console.WriteLine()
        Console.WriteLine("Decoded bytes:")
        Console.WriteLine(decodedString)
    End Sub 'Main
End Class 'ASCIIEncodingExample
C#
using System;
using System.Text;

class ASCIIEncodingExample {
    public static void Main() {
        // The encoding.
        ASCIIEncoding ascii = new ASCIIEncoding();

        // A Unicode string with two characters outside the ASCII code range.
        String unicodeString =
            "This Unicode string contains two characters " +
            "with codes outside the ASCII code range, " +
            "Pi (\u03a0) and Sigma (\u03a3).";
        Console.WriteLine("Original string:");
        Console.WriteLine(unicodeString);

        // Save positions of the special characters for later reference.
        int indexOfPi = unicodeString.IndexOf('\u03a0');
        int indexOfSigma = unicodeString.IndexOf('\u03a3');

        // Encode string.
        Byte[] encodedBytes = ascii.GetBytes(unicodeString);
        Console.WriteLine();
        Console.WriteLine("Encoded bytes:");
        foreach (Byte b in encodedBytes) {
            Console.Write("[{0}]", b);
        }
        Console.WriteLine();

        // Notice that the special characters have been replaced with
        // the value 63, which is the ASCII character code for '?'.
        Console.WriteLine();
        Console.WriteLine(
            "Value at position of Pi character: {0}",
            encodedBytes[indexOfPi]
        );
        Console.WriteLine(
            "Value at position of Sigma character: {0}",
            encodedBytes[indexOfSigma]
        );

        // Decode bytes back to string.
        // Notice missing Pi and Sigma characters.
        String decodedString = ascii.GetString(encodedBytes);
        Console.WriteLine();
        Console.WriteLine("Decoded bytes:");
        Console.WriteLine(decodedString);
    }
}
Visual C++
using namespace System;
using namespace System::Collections;
using namespace System::Text;
int main()
{

   // The encoding.
   ASCIIEncoding^ ascii = gcnew ASCIIEncoding;

   // A Unicode string with two characters outside the ASCII code range.
   String^ unicodeString = "This Unicode String* contains two characters with codes outside the ASCII code range, Pi (\u03a0) and Sigma (\u03a3).";
   Console::WriteLine( "Original String*:" );
   Console::WriteLine( unicodeString );

   // Save positions of the special characters for later reference.
   int indexOfPi = unicodeString->IndexOf( L'\u03a0' );
   int indexOfSigma = unicodeString->IndexOf( L'\u03a3' );

   // Encode string.
   array<Byte>^encodedBytes = ascii->GetBytes( unicodeString );
   Console::WriteLine();
   Console::WriteLine( "Encoded bytes:" );
   IEnumerator^ myEnum = encodedBytes->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Byte b = safe_cast<Byte>(myEnum->Current);
      Console::Write( "->Item[ {0}]", b );
   }

   Console::WriteLine();

   // Notice that the special characters have been replaced with
   // the value 63, which is the ASCII character code for '?'.
   Console::WriteLine();
   Console::WriteLine( "Value at position of Pi character: {0}", encodedBytes[ indexOfPi ] );
   Console::WriteLine( "Value at position of Sigma character: {0}", encodedBytes[ indexOfSigma ] );

   // Decode bytes back to string.
   // Notice missing Pi and Sigma characters.
   String^ decodedString = ascii->GetString( encodedBytes );
   Console::WriteLine();
   Console::WriteLine( "Decoded bytes:" );
   Console::WriteLine( decodedString );
}

System..::.Object
  System.Text..::.Encoding
    System.Text..::.ASCIIEncoding
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
AsciiEncoding Class Using PowerShell      Thomas Lee   |   Edit   |   Show History
# Get-AsciiEncoding.ps1
# Sample using PowerShell
# Thomas Lee - tfl@psp.co.uk

$ascii = new-object System.Text.ASCIIEncoding

# A Unicode string with two characters outside the ASCII code range
$unicodeString = "Pi (Π) and Sigma (♥)"
"Original string ({0} chars long):`n{1}" -f $unicodestring.length,$unicodeString

# Save positions of the special characters for later reference.
$indexOfPi = $unicodeString.IndexOf('Π')
$indexOfSigma = $unicodeString.IndexOf('♥')
"Pi is at position m: {0}" -f $indexofpi
"Sigma is at position: {0}" -f $indexofsigma

# Encode string
$encodedBytes = $ascii.GetBytes($unicodeString)
""
"Encoded bytes:"
foreach ($b in $encodedBytes) {"[{0}]" -f $b }
""

# Notice that the special characters have been replaced with
# the value 63, which is the ASCII character code for '?'.
""
"Value at position of Pi character : {0}" -f $encodedBytes[$indexOfPi]
"Value at position of Sigma character: {0}" -f $encodedBytes[$indexOfSigma]

# Decode bytes back to string.
# Notice missing Pi and Sigma characters.
$decodedString = $ascii.GetString($encodedBytes)
""
"Decoded string:"
$decodedString


This script produces the following output:

PS C:\Users\tfl> 
C:\foo\Get-AsciiEncoding.ps1
Original string (20 chars long):
Pi (Π) and Sigma (♥)
Pi is at position m: 4
Sigma is at position: 18

Encoded bytes:
[80]
[105]
[32]
[40]
[63]
[41]
[32]
[97]
[110]
[100]
[32]
[83]
[105]
[103]
[109]
[97]
[32]
[40]
[63]
[41]


Value at position of Pi character : 63
Value at position of Sigma character: 63

Decoded string:
Pi (?) and Sigma (?)
Error in C# Sample      Thomas Lee   |   Edit   |   Show History
The C# sample is somewhat incorrect. In the unicode string, the sample has code for the 3rd line of the value:
"Pi (\u03a0) and Sigma (\u03a3).";
The "\u03a0" and "\u03a3" should be replaced by the actual Pi and Sigma Character.

Also, note that in PowerShell (and in FireFox), "\u03a3" displays as ♥ not as a sigma. :-(


Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker