.NET Framework Class Library
Encoding.ASCII Property

Gets an encoding for the ASCII (7-bit) character set.

Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)

Syntax

Visual Basic (Declaration)
Public Shared ReadOnly Property ASCII As Encoding
Visual Basic (Usage)
Dim value As Encoding

value = Encoding.ASCII
C#
public static Encoding ASCII { get; }
C++
public:
static property Encoding^ ASCII {
    Encoding^ get ();
}
J#
/** @property */
public static Encoding get_ASCII ()
JScript
public static function get ASCII () : Encoding

Property Value

An Encoding for the ASCII (7-bit) character set.
Remarks

ASCII characters are limited to the lowest 128 Unicode characters, from U+0000 to U+007F.

Example

The following code example demonstrates the effect of the ASCII encoding on characters that are outside the ASCII range.

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

Namespace Encoding_Examples
    Class EncodingExample
        Public Shared Sub Main()
            ' Create and ASCII encoding.
            Dim ascii As Encoding = Encoding.ASCII

            ' 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(&H03A0) & ") and Sigma (" & ChrW(&H03A3) & ")."
            Console.WriteLine("Original string:")
            Console.WriteLine(unicodeString)

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

            ' Encode the 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 a 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
    End Class
End Namespace
C#
using System;
using System.Text;

namespace Encoding_Examples
{
    using System;
    using System.Text;

    class EncodingExample 
    {
        public static void Main() 
        {
            // Create an ASCII encoding.
            Encoding ascii = Encoding.ASCII;
        
            // 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 the positions of the special characters for later reference.
            int indexOfPi = unicodeString.IndexOf('\u03a0');
            int indexOfSigma = unicodeString.IndexOf('\u03a3');

            // Encode the 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 a string.
            // Notice missing the Pi and Sigma characters.
            String decodedString = ascii.GetString(encodedBytes);
            Console.WriteLine();
            Console.WriteLine("Decoded bytes:");
            Console.WriteLine(decodedString);
        }
    }
}
C++
using namespace System;
using namespace System::Text;
using namespace System::Collections;
int main()
{
   
   // Create an ASCII encoding.
   Encoding^ ascii = Encoding::ASCII;
   
   // A Unicode String* with two characters outside the ASCII code range.
   String^ unicodeString = L"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 the positions of the special characters for later reference.
   int indexOfPi = unicodeString->IndexOf( L'\u03a0' );
   int indexOfSigma = unicodeString->IndexOf( L'\u03a3' );
   
   // Encode the 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( "[{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 the missing Pi and Sigma characters.
   String^ decodedString = ascii->GetString( encodedBytes );
   Console::WriteLine();
   Console::WriteLine( "Decoded bytes:" );
   Console::WriteLine( decodedString );
}
J#
package Encoding_Examples ;

import System.* ;
import System.Text.* ;
import System.Byte;

class EncodingExample
{
    public static void main(String[] args)
    {
        // Create an ASCII encoding.
        Encoding ascii = Encoding.get_ASCII();

        // 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 the positions of the special characters for later reference.
        int indexOfPi = unicodeString.IndexOf('\u03a0');
        int indexOfSigma = unicodeString.IndexOf('\u03a0');

        // Encode the string.
        Byte encodedBytes[] = (Byte[])ascii.GetBytes(unicodeString);

        Console.WriteLine();
        Console.WriteLine("Encoded bytes:");

        for (int i = 0; i < encodedBytes.length; i++) {
            Byte b = encodedBytes[i];
            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.get_Item(indexOfPi));
        Console.WriteLine("Value at position of Sigma character: {0}", 
                encodedBytes.get_Item(indexOfSigma));

        // Decode bytes back to a string.
        // Notice missing the Pi and Sigma characters.
        String decodedString = ascii.GetString((ubyte[])encodedBytes);

        Console.WriteLine();
        Console.WriteLine("Decoded bytes:");
        Console.WriteLine(decodedString);
    }
}
Platforms

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

Version Information

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0
See Also

Tags :


Community Content

Shawn Steele [MSFT]
Consider if ASCII is an appropriate choice for your application.

Note that many people say "ASCII" when they are really talking about 8 bit encodings like windows-1252.  When choosing ASCII try to consider if its the best choice.  Some things to consider.

Some protocols require ASCII, or a subset thereof.  In these cases ASCII is likely appropriate.
If an 8-bit encoding is expected, then ASCII probably isn't correct.
Consider using UTF8 instead of ASCII.  For the characters 0-7F the results are identical, but UTF-8 has the additional advantage that all Unicode characters are representable, which avoids data loss.
Attackers could attempt to use the 8th bit in a maliceous fashion.  In .Net 2.0 those characters will go through the fallback (ie: turn into ?), but other encodings like UTF-8 could remove any ambiguity in this case.


 

Tags :

Shawn Steele [MSFT]
Is the default ASCII behavior "right" for you?

Note that the default constructor by itself may not have the appropriate behavior for your application.  You may want to consider changing the Encoder/DecoderFallbacks to Encoder/DecoderExceptionFallback to prevent sequences with the 8th bit set.  You may also want custom behavior for those cases.

See class topic for more info about ASCIIEncoding.

 

Tags :

Shawn Steele [MSFT]
ASCII is only 7 bits
Previous versions of .Net allowed spoofing by merely ignoring the 8th bit.  That was modified so that now non-ASCII code points will fall back (turn into ?) when decoding bytes.
Tags :

Red Bill
ASCII extended to 8 bits: ISO-8859-1
Often 8 bit versions of ASCII are needed and ISO-8859-1 is a standard that seems quite common. An encoding for this can be obtained using code page 28591 with Encoding.GetEncoding(28591);

Page view tracker