Encoding.ASCII Propriété
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Obtient un encodage pour le jeu de caractères ASCII (7 bits).
public:
static property System::Text::Encoding ^ ASCII { System::Text::Encoding ^ get(); };
public static System.Text.Encoding ASCII { get; }
static member ASCII : System.Text.Encoding
Public Shared ReadOnly Property ASCII As Encoding
Valeur de propriété
Encodage pour le jeu de caractères ASCII (7 bits).
Exemples
L’exemple suivant illustre l’effet de l’encodage ASCII sur les caractères qui se trouvent en dehors de la plage ASCII.
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 );
}
/*
This code produces the following output.
Original string:
This unicode string contains two characters with codes outside the ASCII code range, Pi (Π) and Sigma (Σ).
Encoded bytes:
[84][104][105][115][32][117][110][105][99][111][100][101][32][115][116][114][105][110][103][32][99][111][110][116][97][105][110][115][32][116][119][111][32][99][104][97][114][97][99][116][101][114][115][32][119][105][116][104][32][99][111][100][101][115][32][111][117][116][115][105][100][101][32][116][104][101][32][65][83][67][73][73][32][99][111][100][101][32][114][97][110][103][101][44][32][80][105][32][40][63][41][32][97][110][100][32][83][105][103][109][97][32][40][63][41][46]
Value at position of Pi character: 63
Value at position of Sigma character: 63
Decoded bytes:
This unicode string contains two characters with codes outside the ASCII code range, Pi (?) and Sigma (?).
*/
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);
}
}
/*
This code produces the following output.
Original string:
This unicode string contains two characters with codes outside the ASCII code range, Pi (Π) and Sigma (Σ).
Encoded bytes:
[84][104][105][115][32][117][110][105][99][111][100][101][32][115][116][114][105][110][103][32][99][111][110][116][97][105][110][115][32][116][119][111][32][99][104][97][114][97][99][116][101][114][115][32][119][105][116][104][32][99][111][100][101][115][32][111][117][116][115][105][100][101][32][116][104][101][32][65][83][67][73][73][32][99][111][100][101][32][114][97][110][103][101][44][32][80][105][32][40][63][41][32][97][110][100][32][83][105][103][109][97][32][40][63][41][46]
Value at position of Pi character: 63
Value at position of Sigma character: 63
Decoded bytes:
This unicode string contains two characters with codes outside the ASCII code range, Pi (?) and Sigma (?).
*/
Imports System.Text
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:")
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
'This code produces the following output.
'Original string:
'This unicode string contains two characters with codes outside the ASCII code range, Pi (Π) and Sigma (Σ).
'
'Encoded bytes:
'[84][104][105][115][32][117][110][105][99][111][100][101][32]'[115][116][114][105][110][103][32][99][111][110][116][97]'[105][110][115][32][116][119][111][32][99][104][97][114][97]'[99][116][101][114][115][32][119][105][116][104][32][99][111]'[100][101][115][32][111][117][116][115][105][100][101][32]'[116][104][101][32][65][83][67][73][73][32][99][111][100]'[101][32][114][97][110][103][101][44][32][80][105][32][40]'[63][41][32][97][110][100][32][83][105][103][109][97][32][40]'[63][41][46]
'
'Value at position of Pi character: 63
'Value at position of Sigma character: 63
'
'Decoded bytes:
'This unicode string contains two characters with codes outside 'the ASCII code range, Pi (?) and Sigma (?).
'
Remarques
Les caractères ASCII sont limités aux 128 caractères Unicode les plus faibles, de U + 0000 à U + 007F.
Lorsque vous sélectionnez l’encodage ASCII de votre application, prenez en compte les éléments suivants :
L’encodage ASCII convient généralement aux protocoles qui requièrent ASCII.
Si vous avez besoin d’un encodage 8 bits (parfois appelé « ASCII »), l’encodage UTF-8 est recommandé par rapport à l’encodage ASCII. Pour les caractères 0 à 7F, les résultats sont identiques, mais l’utilisation d’UTF-8 évite la perte de données en autorisant la représentation de tous les caractères Unicode qui peuvent être représentables. Notez que l’encodage ASCII a une ambiguïté de 8 bits qui peut permettre une utilisation malveillante, mais l’encodage UTF-8 supprime l’ambiguïté sur le 8ème bit.
Avant .NET Framework version 2,0, .NET Framework autorisé l’usurpation d’identité en ignorant le 8ème bit. À partir de .NET Framework 2,0, les points de code non-ASCII sont restaurés au cours du décodage.
L' ASCIIEncoding objet retourné par cette propriété peut ne pas avoir le comportement approprié pour votre application. Elle utilise l’option de secours de remplacement pour remplacer chaque chaîne qu’elle ne peut pas encoder et chaque octet qu’elle ne peut pas décoder par un point d’interrogation (« ? »). Au lieu de cela, vous pouvez appeler la GetEncoding(String, EncoderFallback, DecoderFallback) méthode pour instancier un ASCIIEncoding objet dont EncoderFallbackException la valeur de secours est ou DecoderFallbackException , comme l’illustre l’exemple suivant.
using System;
using System.Text;
public class Example
{
public static void Main()
{
Encoding enc = Encoding.GetEncoding("us-ascii",
new EncoderExceptionFallback(),
new DecoderExceptionFallback());
string value = "\u00C4 \u00F6 \u00AE";
try {
byte[] bytes= enc.GetBytes(value);
foreach (var byt in bytes)
Console.Write("{0:X2} ", byt);
Console.WriteLine();
string value2 = enc.GetString(bytes);
Console.WriteLine(value2);
}
catch (EncoderFallbackException e) {
Console.WriteLine("Unable to encode {0} at index {1}",
e.IsUnknownSurrogate() ?
String.Format("U+{0:X4} U+{1:X4}",
Convert.ToUInt16(e.CharUnknownHigh),
Convert.ToUInt16(e.CharUnknownLow)) :
String.Format("U+{0:X4}",
Convert.ToUInt16(e.CharUnknown)),
e.Index);
}
}
}
// The example displays the following output:
// Unable to encode U+00C4 at index 0
Imports System.Text
Module Example
Public Sub Main()
Dim enc As Encoding = Encoding.GetEncoding("us-ascii",
New EncoderExceptionFallback(),
New DecoderExceptionFallback())
Dim value As String = String.Format("{0} {1} {2}",
ChrW(&h00C4), ChrW(&h00F6), ChrW(&h00AE))
Try
Dim bytes() As Byte = enc.GetBytes(value)
For Each byt As Byte In bytes
Console.Write("{0:X2} ", byt)
Next
Console.WriteLine()
Dim value2 As String = enc.GetString(bytes)
Console.WriteLine(value2)
Catch e As EncoderFallbackException
Console.WriteLine("Unable to encode {0} at index {1}",
If(e.IsUnknownSurrogate(),
String.Format("U+{0:X4} U+{1:X4}",
Convert.ToUInt16(e.CharUnknownHigh),
Convert.ToUInt16(e.CharUnknownLow)),
String.Format("U+{0:X4}",
Convert.ToUInt16(e.CharUnknown))),
e.Index)
End Try
End Sub
End Module
' The example displays the following output:
' Unable to encode U+00C4 at index 0