Encoding.GetEncoding Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Restituisce una codifica per la tabella codici specificata.
Overload
| Nome | Descrizione |
|---|---|
| GetEncoding(Int32) |
Restituisce la codifica associata all'identificatore della tabella codici specificato. |
| GetEncoding(String) |
Restituisce la codifica associata al nome della tabella codici specificato. |
| GetEncoding(Int32, EncoderFallback, DecoderFallback) |
Restituisce la codifica associata all'identificatore della tabella codici specificato. I parametri specificano un gestore errori per i caratteri che non possono essere codificati e sequenze di byte che non possono essere decodificate. |
| GetEncoding(String, EncoderFallback, DecoderFallback) |
Restituisce la codifica associata al nome della tabella codici specificato. I parametri specificano un gestore errori per i caratteri che non possono essere codificati e sequenze di byte che non possono essere decodificate. |
GetEncoding(Int32)
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
Restituisce la codifica associata all'identificatore della tabella codici specificato.
public:
static System::Text::Encoding ^ GetEncoding(int codepage);
public static System.Text.Encoding GetEncoding(int codepage);
static member GetEncoding : int -> System.Text.Encoding
Public Shared Function GetEncoding (codepage As Integer) As Encoding
Parametri
- codepage
- Int32
Identificatore della tabella codici della codifica preferita. Per un elenco dei valori possibili, vedere Encoding.
oppure
0 (zero), per usare la codifica predefinita.
Restituisce
Codifica associata alla tabella codici specificata.
Eccezioni
codepage è minore di zero o maggiore di 65535.
codepage non è supportato dalla piattaforma sottostante.
codepage non è supportato dalla piattaforma sottostante.
Esempio
Nell'esempio seguente vengono recuperate due istanze della stessa codifica (una per tabella codici e un'altra per nome) e ne verifica l'uguaglianza.
using System;
using System.Text;
public class SamplesEncoding {
public static void Main() {
// Get a UTF-32 encoding by codepage.
Encoding e1 = Encoding.GetEncoding( 12000 );
// Get a UTF-32 encoding by name.
Encoding e2 = Encoding.GetEncoding( "utf-32" );
// Check their equality.
Console.WriteLine( "e1 equals e2? {0}", e1.Equals( e2 ) );
}
}
/*
This code produces the following output.
e1 equals e2? True
*/
Imports System.Text
Public Class SamplesEncoding
Public Shared Sub Main()
' Get a UTF-32 encoding by codepage.
Dim e1 As Encoding = Encoding.GetEncoding(12000)
' Get a UTF-32 encoding by name.
Dim e2 As Encoding = Encoding.GetEncoding("utf-32")
' Check their equality.
Console.WriteLine("e1 equals e2? {0}", e1.Equals(e2))
End Sub
End Class
'This code produces the following output.
'
'e1 equals e2? True
Commenti
Il gestore di fallback dipende dal tipo di codifica di codepage. Se codepage è una tabella codici o una codifica DBCS (Double-Byte Character Set), viene usato un gestore di fallback più adatto. In caso contrario, viene usato un gestore di fallback sostitutivo. Questi gestori di fallback potrebbero non essere appropriati per l'app. Per specificare il gestore di fallback usato dalla codifica specificata da codepage, è possibile chiamare l'overload GetEncoding(Int32, EncoderFallback, DecoderFallback) .
In .NET Framework il GetEncoding metodo si basa sulla piattaforma sottostante per supportare la maggior parte delle tabelle codici. .NET Framework supporta tuttavia in modo nativo alcune codifiche. Per un elenco delle tabelle codici, vedere Elenco delle codifiche. In .NET Core il GetEncoding metodo restituisce le codifiche supportate in modo nativo da .NET Core. In entrambe le implementazioni di .NET è possibile chiamare il GetEncodings metodo per ottenere una matrice di EncodingInfo oggetti che contiene informazioni su tutte le codifiche disponibili.
Oltre alle codifiche disponibili in modo nativo in .NET Core o supportate intrinsecamente in una versione specifica della piattaforma di .NET Framework, il GetEncoding metodo restituisce eventuali codifiche aggiuntive rese disponibili registrando un EncodingProvider oggetto . Se la stessa codifica è stata registrata da più EncodingProvider oggetti, questo metodo restituisce l'ultimo oggetto registrato.
È anche possibile specificare un valore pari a 0 per l'argomento codepage . Il comportamento varia tra .NET Framework e .NET Core e versioni successive:
In .NET Framework: restituisce sempre la codifica corrispondente alla tabella codici attiva del sistema in Windows. Si tratta della stessa codifica restituita dalla Encoding.Default proprietà .
In .NET Core e versioni successive: il comportamento dipende dalla configurazione di codifica dell'applicazione:
Nessun provider di codifica registrato: restituisce un oggetto UTF8Encoding, uguale a Encoding.Default.
CodePagesEncodingProvider registrato:
- In Windows restituisce la codifica corrispondente alla tabella codici attiva del sistema (uguale al comportamento di .NET Framework).
- Nelle piattaforme non Windows restituisce sempre un oggetto UTF8Encoding.
Un provider diverso registrato: il comportamento è determinato da tale provider. Per informazioni dettagliate, vedere la relativa documentazione. Se vengono registrati più provider, il metodo restituisce la codifica dall'ultimo provider registrato che gestisce un
codepageargomento pari a 0.
Annotazioni
- Alcune tabelle codici non supportate generano un'eccezione ArgumentException , mentre altre causano un oggetto NotSupportedException. Pertanto, il codice deve intercettare tutte le eccezioni indicate nella sezione Eccezioni.
- In .NET 5 e versioni successive l'identificatore
65000della tabella codici , che rappresenta UTF-7, non è supportato.
Annotazioni
Le tabelle codici ANSI possono essere diverse in computer diversi e possono cambiare in un singolo computer, causando il danneggiamento dei dati. Per questo motivo, se la tabella codici attiva è una tabella codici ANSI, la codifica e la decodifica dei dati usando la tabella codici predefinita restituita da Encoding.GetEncoding(0) non è consigliabile. Per i risultati più coerenti, è consigliabile usare una codifica Unicode, ad esempio UTF-8 (tabella codici 65001) o UTF-16, anziché una tabella codici specifica.
GetEncoding restituisce un'istanza memorizzata nella cache con le impostazioni predefinite. È consigliabile usare i costruttori delle classi derivate per ottenere un'istanza con impostazioni diverse. Ad esempio, la UTF32Encoding classe fornisce un costruttore che consente di abilitare il rilevamento degli errori.
Vedi anche
- CodePage
- EncoderFallback
- EncoderFallback
- GetEncodings()
- Come usare le classi di codifica dei caratteri in .NET
Si applica a
GetEncoding(String)
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
Restituisce la codifica associata al nome della tabella codici specificato.
public:
static System::Text::Encoding ^ GetEncoding(System::String ^ name);
public static System.Text.Encoding GetEncoding(string name);
static member GetEncoding : string -> System.Text.Encoding
Public Shared Function GetEncoding (name As String) As Encoding
Parametri
- name
- String
Nome della tabella codici della codifica preferita. Qualsiasi valore restituito dalla WebName proprietà è valido. Per un elenco dei valori possibili, vedere Encoding.
Restituisce
Codifica associata alla tabella codici specificata.
Eccezioni
name non è un nome di tabella codici valido.
oppure
La tabella codici indicata da name non è supportata dalla piattaforma sottostante.
Esempio
Nell'esempio seguente vengono recuperate due istanze della stessa codifica (una per tabella codici e un'altra per nome) e ne verifica l'uguaglianza.
using System;
using System.Text;
public class SamplesEncoding {
public static void Main() {
// Get a UTF-32 encoding by codepage.
Encoding e1 = Encoding.GetEncoding( 12000 );
// Get a UTF-32 encoding by name.
Encoding e2 = Encoding.GetEncoding( "utf-32" );
// Check their equality.
Console.WriteLine( "e1 equals e2? {0}", e1.Equals( e2 ) );
}
}
/*
This code produces the following output.
e1 equals e2? True
*/
Imports System.Text
Public Class SamplesEncoding
Public Shared Sub Main()
' Get a UTF-32 encoding by codepage.
Dim e1 As Encoding = Encoding.GetEncoding(12000)
' Get a UTF-32 encoding by name.
Dim e2 As Encoding = Encoding.GetEncoding("utf-32")
' Check their equality.
Console.WriteLine("e1 equals e2? {0}", e1.Equals(e2))
End Sub
End Class
'This code produces the following output.
'
'e1 equals e2? True
Commenti
Il gestore di fallback dipende dal tipo di codifica di name. Se name è una tabella codici o una codifica DBCS (Double-Byte Character Set), viene usato un gestore di fallback più adatto. In caso contrario, viene usato un gestore di fallback sostitutivo. Questi gestori di fallback potrebbero non essere appropriati per l'app. Per specificare il gestore di fallback usato dalla codifica specificata da name, è possibile chiamare l'overload GetEncoding(String, EncoderFallback, DecoderFallback) .
In .NET Framework il GetEncoding metodo si basa sulla piattaforma sottostante per supportare la maggior parte delle tabelle codici. .NET Framework supporta tuttavia in modo nativo alcune codifiche. Per un elenco delle tabelle codici, vedere Elenco delle codifiche. In .NET Core il GetEncoding metodo restituisce le codifiche supportate in modo nativo da .NET Core. In entrambe le implementazioni di .NET è possibile chiamare il GetEncodings metodo per ottenere una matrice di EncodingInfo oggetti che contiene informazioni su tutte le codifiche disponibili.
Oltre alle codifiche disponibili in modo nativo in .NET Core o supportate intrinsecamente in una versione specifica della piattaforma di .NET Framework, il GetEncoding metodo restituisce eventuali codifiche aggiuntive rese disponibili registrando un EncodingProvider oggetto . Se la stessa codifica è stata registrata da più EncodingProvider oggetti, questo metodo restituisce l'ultimo oggetto registrato.
In .NET 5 e versioni successive il nome utf-7 della tabella codici non è supportato.
Annotazioni
Le tabelle codici ANSI possono essere diverse in computer diversi oppure possono essere modificate per un singolo computer, causando il danneggiamento dei dati. Per i risultati più coerenti, usare Unicode, ad esempio UTF-8 (tabella codici 65001) o UTF-16, anziché una tabella codici specifica.
GetEncoding restituisce un'istanza memorizzata nella cache con le impostazioni predefinite. È consigliabile usare i costruttori delle classi derivate per ottenere un'istanza con impostazioni diverse. Ad esempio, la UTF32Encoding classe fornisce un costruttore che consente di abilitare il rilevamento degli errori.
Vedi anche
- EncoderFallback
- EncoderFallback
- GetEncodings()
- Come usare le classi di codifica dei caratteri in .NET
Si applica a
GetEncoding(Int32, EncoderFallback, DecoderFallback)
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
Restituisce la codifica associata all'identificatore della tabella codici specificato. I parametri specificano un gestore errori per i caratteri che non possono essere codificati e sequenze di byte che non possono essere decodificate.
public:
static System::Text::Encoding ^ GetEncoding(int codepage, System::Text::EncoderFallback ^ encoderFallback, System::Text::DecoderFallback ^ decoderFallback);
public static System.Text.Encoding GetEncoding(int codepage, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback);
static member GetEncoding : int * System.Text.EncoderFallback * System.Text.DecoderFallback -> System.Text.Encoding
Public Shared Function GetEncoding (codepage As Integer, encoderFallback As EncoderFallback, decoderFallback As DecoderFallback) As Encoding
Parametri
- codepage
- Int32
Identificatore della tabella codici della codifica preferita. Per un elenco dei valori possibili, vedere Encoding.
oppure
0 (zero), per usare la codifica predefinita.
- encoderFallback
- EncoderFallback
Oggetto che fornisce una procedura di gestione degli errori quando un carattere non può essere codificato con la codifica corrente.
- decoderFallback
- DecoderFallback
Oggetto che fornisce una procedura di gestione degli errori quando una sequenza di byte non può essere decodificata con la codifica corrente.
Restituisce
Codifica associata alla tabella codici specificata.
Eccezioni
codepage è minore di zero o maggiore di 65535.
codepage non è supportato dalla piattaforma sottostante.
codepage non è supportato dalla piattaforma sottostante.
Esempio
Nell'esempio seguente viene illustrato il Encoding.GetEncoding(String, EncoderFallback, DecoderFallback) metodo .
// This example demonstrates the EncoderReplacementFallback class.
using System;
using System.Text;
class Sample
{
public static void Main()
{
// Create an encoding, which is equivalent to calling the
// ASCIIEncoding class constructor.
// The EncoderReplacementFallback parameter specifies that the
// string, "(unknown)", replace characters that cannot be encoded.
// A decoder replacement fallback is also specified, but in this
// code example the decoding operation cannot fail.
Encoding ae = Encoding.GetEncoding(
"us-ascii",
new EncoderReplacementFallback("(unknown)"),
new DecoderReplacementFallback("(error)"));
// The input string consists of the Unicode characters LEFT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00BB).
// The encoding can only encode characters in the US-ASCII range of U+0000
// through U+007F. Consequently, the characters bracketing the 'X' character
// are replaced with the fallback replacement string, "(unknown)".
string inputString = "\u00abX\u00bb";
string decodedString;
string twoNewLines = "\n\n";
byte[] encodedBytes = new byte[ae.GetByteCount(inputString)];
int numberOfEncodedBytes = 0;
int ix = 0;
// --------------------------------------------------------------------------
// Display the name of the encoding.
Console.WriteLine("The name of the encoding is \"{0}\".\n", ae.WebName);
// Display the input string in text.
Console.WriteLine("Input string ({0} characters): \"{1}\"",
inputString.Length, inputString);
// Display the input string in hexadecimal.
Console.Write("Input string in hexadecimal: ");
foreach (char c in inputString.ToCharArray())
{
Console.Write("0x{0:X2} ", (int)c);
}
Console.Write(twoNewLines);
// --------------------------------------------------------------------------
// Encode the input string.
Console.WriteLine("Encode the input string...");
numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length,
encodedBytes, 0);
// Display the encoded bytes.
Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):\n",
numberOfEncodedBytes);
ix = 0;
foreach (byte b in encodedBytes)
{
Console.Write("0x{0:X2} ", (int)b);
ix++;
if (0 == ix % 6) Console.WriteLine();
}
Console.Write(twoNewLines);
// --------------------------------------------------------------------------
// Decode the encoded bytes, yielding a reconstituted string.
Console.WriteLine("Decode the encoded bytes...");
decodedString = ae.GetString(encodedBytes);
// Display the input string and the decoded string for comparison.
Console.WriteLine("Input string: \"{0}\"", inputString);
Console.WriteLine("Decoded string:\"{0}\"", decodedString);
}
}
/*
This code example produces the following results:
The name of the encoding is "us-ascii".
Input string (3 characters): "«X»"
Input string in hexadecimal: 0xAB 0x58 0xBB
Encode the input string...
Encoded bytes in hexadecimal (19 bytes):
0x28 0x75 0x6E 0x6B 0x6E 0x6F
0x77 0x6E 0x29 0x58 0x28 0x75
0x6E 0x6B 0x6E 0x6F 0x77 0x6E
0x29
Decode the encoded bytes...
Input string: "«X»"
Decoded string:"(unknown)X(unknown)"
*/
' This example demonstrates the EncoderReplacementFallback class.
Imports System.Text
Class Sample
Public Shared Sub Main()
' Create an encoding, which is equivalent to calling the
' ASCIIEncoding class constructor.
' The EncoderReplacementFallback parameter specifies that the
' string, "(unknown)", replace characters that cannot be encoded.
' A decoder replacement fallback is also specified, but in this
' code example the decoding operation cannot fail.
Dim erf As New EncoderReplacementFallback("(unknown)")
Dim drf As New DecoderReplacementFallback("(error)")
Dim ae As Encoding = Encoding.GetEncoding("us-ascii", erf, drf)
' The input string consists of the Unicode characters LEFT POINTING
' DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING
' DOUBLE ANGLE QUOTATION MARK (U+00BB).
' The encoding can only encode characters in the US-ASCII range of U+0000
' through U+007F. Consequently, the characters bracketing the 'X' character
' are replaced with the fallback replacement string, "(unknown)".
Dim inputString As String = "«X»"
Dim decodedString As String
Dim twoNewLines As String = vbCrLf & vbCrLf
Dim ix As Integer = 0
Dim numberOfEncodedBytes As Integer = ae.GetByteCount(inputString)
' Counteract the compiler adding an extra byte to the array.
Dim encodedBytes(numberOfEncodedBytes - 1) As Byte
' --------------------------------------------------------------------------
' Display the name of the encoding.
Console.WriteLine("The name of the encoding is ""{0}""." & vbCrLf, ae.WebName)
' Display the input string in text.
Console.WriteLine("Input string ({0} characters): ""{1}""", _
inputString.Length, inputString)
' Display the input string in hexadecimal.
' Each element is converted to an integer with Convert.ToInt32.
Console.Write("Input string in hexadecimal: ")
Dim c As Char
For Each c In inputString.ToCharArray()
Console.Write("0x{0:X2} ", Convert.ToInt32(c))
Next c
Console.Write(twoNewLines)
' --------------------------------------------------------------------------
' Encode the input string.
Console.WriteLine("Encode the input string...")
numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length, _
encodedBytes, 0)
' Display the encoded bytes.
' Each element is converted to an integer with Convert.ToInt32.
Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):" & vbCrLf, _
numberOfEncodedBytes)
ix = 0
Dim b As Byte
For Each b In encodedBytes
Console.Write("0x{0:X2} ", Convert.ToInt32(b))
ix += 1
If 0 = ix Mod 6 Then
Console.WriteLine()
End If
Next b
Console.Write(twoNewLines)
' --------------------------------------------------------------------------
' Decode the encoded bytes, yielding a reconstituted string.
Console.WriteLine("Decode the encoded bytes...")
decodedString = ae.GetString(encodedBytes)
' Display the input string and the decoded string for comparison.
Console.WriteLine("Input string: ""{0}""", inputString)
Console.WriteLine("Decoded string:""{0}""", decodedString)
End Sub
End Class
'
'This code example produces the following results:
'
'The name of the encoding is "us-ascii".
'
'Input string (3 characters): "X"
'Input string in hexadecimal: 0xAB 0x58 0xBB
'
'Encode the input string...
'Encoded bytes in hexadecimal (19 bytes):
'
'0x28 0x75 0x6E 0x6B 0x6E 0x6F
'0x77 0x6E 0x29 0x58 0x28 0x75
'0x6E 0x6B 0x6E 0x6F 0x77 0x6E
'0x29
'
'Decode the encoded bytes...
'Input string: "X"
'Decoded string:"(unknown)X(unknown)"
'
Commenti
Annotazioni
- Alcune tabelle codici non supportate causano la generazione dell'eccezione ArgumentException , mentre altre causano NotSupportedException. Pertanto, il codice deve intercettare tutte le eccezioni indicate nella sezione Eccezioni.
- In .NET 5 e versioni successive l'identificatore
65000della tabella codici , che rappresenta UTF-7, non è supportato.
In .NET Framework il GetEncoding metodo si basa sulla piattaforma sottostante per supportare la maggior parte delle tabelle codici. .NET Framework supporta tuttavia in modo nativo alcune codifiche. Per un elenco delle tabelle codici, vedere Elenco delle codifiche. In .NET Core il GetEncoding metodo restituisce le codifiche supportate in modo nativo da .NET Core. In entrambe le implementazioni di .NET è possibile chiamare il GetEncodings metodo per ottenere una matrice di EncodingInfo oggetti che contiene informazioni su tutte le codifiche disponibili.
Oltre alle codifiche disponibili in modo nativo in .NET Core o supportate intrinsecamente in una versione specifica della piattaforma di .NET Framework, il GetEncoding metodo restituisce eventuali codifiche aggiuntive rese disponibili registrando un EncodingProvider oggetto . Se la stessa codifica è stata registrata da più EncodingProvider oggetti, questo metodo restituisce l'ultimo oggetto registrato.
È anche possibile specificare un valore pari a 0 per l'argomento codepage . Il comportamento varia tra .NET Framework e .NET Core e versioni successive:
In .NET Framework: restituisce sempre la codifica corrispondente alla tabella codici attiva del sistema in Windows. Si tratta della stessa codifica restituita dalla Encoding.Default proprietà .
In .NET Core e versioni successive: il comportamento dipende dalla configurazione di codifica dell'applicazione:
Nessun provider di codifica registrato: restituisce un oggetto UTF8Encoding, uguale a Encoding.Default.
CodePagesEncodingProvider registrato:
- In Windows restituisce la codifica corrispondente alla tabella codici attiva del sistema (uguale al comportamento di .NET Framework).
- Nelle piattaforme non Windows restituisce sempre un oggetto UTF8Encoding.
Un provider diverso registrato: il comportamento è determinato da tale provider. Per informazioni dettagliate, vedere la relativa documentazione. Se vengono registrati più provider, il metodo restituisce la codifica dall'ultimo provider registrato che gestisce un
codepageargomento pari a 0.
Annotazioni
Le tabelle codici ANSI possono essere diverse in computer diversi e possono cambiare in un singolo computer, causando il danneggiamento dei dati. Per questo motivo, se la tabella codici attiva è una tabella codici ANSI, la codifica e la decodifica dei dati usando la tabella codici predefinita restituita da Encoding.GetEncoding(0) non è consigliabile. Per i risultati più coerenti, è consigliabile usare Unicode, ad esempio UTF-8 (tabella codici 65001) o UTF-16, anziché una tabella codici specifica.
Per ottenere la codifica associata alla tabella codici attiva, è possibile specificare il valore 0 per l'argomento codepage oppure, se il codice è in esecuzione in .NET Framework, recuperare il valore della Encoding.Default proprietà. Per determinare la tabella codici attiva corrente, chiamare la funzione GetACP di Windows da .NET Framework.
GetEncoding restituisce un'istanza memorizzata nella cache con le impostazioni predefinite. È consigliabile usare i costruttori delle classi derivate per ottenere un'istanza con impostazioni diverse. Ad esempio, la UTF32Encoding classe fornisce un costruttore che consente di abilitare il rilevamento degli errori.
Vedi anche
- CodePage
- EncoderFallback
- EncoderFallback
- GetEncodings()
- Come usare le classi di codifica dei caratteri in .NET
Si applica a
GetEncoding(String, EncoderFallback, DecoderFallback)
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
- Origine:
- Encoding.cs
Restituisce la codifica associata al nome della tabella codici specificato. I parametri specificano un gestore errori per i caratteri che non possono essere codificati e sequenze di byte che non possono essere decodificate.
public:
static System::Text::Encoding ^ GetEncoding(System::String ^ name, System::Text::EncoderFallback ^ encoderFallback, System::Text::DecoderFallback ^ decoderFallback);
public static System.Text.Encoding GetEncoding(string name, System.Text.EncoderFallback encoderFallback, System.Text.DecoderFallback decoderFallback);
static member GetEncoding : string * System.Text.EncoderFallback * System.Text.DecoderFallback -> System.Text.Encoding
Public Shared Function GetEncoding (name As String, encoderFallback As EncoderFallback, decoderFallback As DecoderFallback) As Encoding
Parametri
- name
- String
Nome della tabella codici della codifica preferita. Qualsiasi valore restituito dalla WebName proprietà è valido. I valori possibili sono elencati nella colonna Name della tabella visualizzata nell'argomento Encoding della classe .
- encoderFallback
- EncoderFallback
Oggetto che fornisce una procedura di gestione degli errori quando un carattere non può essere codificato con la codifica corrente.
- decoderFallback
- DecoderFallback
Oggetto che fornisce una procedura di gestione degli errori quando una sequenza di byte non può essere decodificata con la codifica corrente.
Restituisce
Codifica associata alla tabella codici specificata.
Eccezioni
name non è un nome di tabella codici valido.
oppure
La tabella codici indicata da name non è supportata dalla piattaforma sottostante.
Esempio
Nell'esempio seguente viene illustrato il Encoding.GetEncoding(String, EncoderFallback, DecoderFallback) metodo .
// This example demonstrates the EncoderReplacementFallback class.
using System;
using System.Text;
class Sample
{
public static void Main()
{
// Create an encoding, which is equivalent to calling the
// ASCIIEncoding class constructor.
// The EncoderReplacementFallback parameter specifies that the
// string, "(unknown)", replace characters that cannot be encoded.
// A decoder replacement fallback is also specified, but in this
// code example the decoding operation cannot fail.
Encoding ae = Encoding.GetEncoding(
"us-ascii",
new EncoderReplacementFallback("(unknown)"),
new DecoderReplacementFallback("(error)"));
// The input string consists of the Unicode characters LEFT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING
// DOUBLE ANGLE QUOTATION MARK (U+00BB).
// The encoding can only encode characters in the US-ASCII range of U+0000
// through U+007F. Consequently, the characters bracketing the 'X' character
// are replaced with the fallback replacement string, "(unknown)".
string inputString = "\u00abX\u00bb";
string decodedString;
string twoNewLines = "\n\n";
byte[] encodedBytes = new byte[ae.GetByteCount(inputString)];
int numberOfEncodedBytes = 0;
int ix = 0;
// --------------------------------------------------------------------------
// Display the name of the encoding.
Console.WriteLine("The name of the encoding is \"{0}\".\n", ae.WebName);
// Display the input string in text.
Console.WriteLine("Input string ({0} characters): \"{1}\"",
inputString.Length, inputString);
// Display the input string in hexadecimal.
Console.Write("Input string in hexadecimal: ");
foreach (char c in inputString.ToCharArray())
{
Console.Write("0x{0:X2} ", (int)c);
}
Console.Write(twoNewLines);
// --------------------------------------------------------------------------
// Encode the input string.
Console.WriteLine("Encode the input string...");
numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length,
encodedBytes, 0);
// Display the encoded bytes.
Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):\n",
numberOfEncodedBytes);
ix = 0;
foreach (byte b in encodedBytes)
{
Console.Write("0x{0:X2} ", (int)b);
ix++;
if (0 == ix % 6) Console.WriteLine();
}
Console.Write(twoNewLines);
// --------------------------------------------------------------------------
// Decode the encoded bytes, yielding a reconstituted string.
Console.WriteLine("Decode the encoded bytes...");
decodedString = ae.GetString(encodedBytes);
// Display the input string and the decoded string for comparison.
Console.WriteLine("Input string: \"{0}\"", inputString);
Console.WriteLine("Decoded string:\"{0}\"", decodedString);
}
}
/*
This code example produces the following results:
The name of the encoding is "us-ascii".
Input string (3 characters): "«X»"
Input string in hexadecimal: 0xAB 0x58 0xBB
Encode the input string...
Encoded bytes in hexadecimal (19 bytes):
0x28 0x75 0x6E 0x6B 0x6E 0x6F
0x77 0x6E 0x29 0x58 0x28 0x75
0x6E 0x6B 0x6E 0x6F 0x77 0x6E
0x29
Decode the encoded bytes...
Input string: "«X»"
Decoded string:"(unknown)X(unknown)"
*/
' This example demonstrates the EncoderReplacementFallback class.
Imports System.Text
Class Sample
Public Shared Sub Main()
' Create an encoding, which is equivalent to calling the
' ASCIIEncoding class constructor.
' The EncoderReplacementFallback parameter specifies that the
' string, "(unknown)", replace characters that cannot be encoded.
' A decoder replacement fallback is also specified, but in this
' code example the decoding operation cannot fail.
Dim erf As New EncoderReplacementFallback("(unknown)")
Dim drf As New DecoderReplacementFallback("(error)")
Dim ae As Encoding = Encoding.GetEncoding("us-ascii", erf, drf)
' The input string consists of the Unicode characters LEFT POINTING
' DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING
' DOUBLE ANGLE QUOTATION MARK (U+00BB).
' The encoding can only encode characters in the US-ASCII range of U+0000
' through U+007F. Consequently, the characters bracketing the 'X' character
' are replaced with the fallback replacement string, "(unknown)".
Dim inputString As String = "«X»"
Dim decodedString As String
Dim twoNewLines As String = vbCrLf & vbCrLf
Dim ix As Integer = 0
Dim numberOfEncodedBytes As Integer = ae.GetByteCount(inputString)
' Counteract the compiler adding an extra byte to the array.
Dim encodedBytes(numberOfEncodedBytes - 1) As Byte
' --------------------------------------------------------------------------
' Display the name of the encoding.
Console.WriteLine("The name of the encoding is ""{0}""." & vbCrLf, ae.WebName)
' Display the input string in text.
Console.WriteLine("Input string ({0} characters): ""{1}""", _
inputString.Length, inputString)
' Display the input string in hexadecimal.
' Each element is converted to an integer with Convert.ToInt32.
Console.Write("Input string in hexadecimal: ")
Dim c As Char
For Each c In inputString.ToCharArray()
Console.Write("0x{0:X2} ", Convert.ToInt32(c))
Next c
Console.Write(twoNewLines)
' --------------------------------------------------------------------------
' Encode the input string.
Console.WriteLine("Encode the input string...")
numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length, _
encodedBytes, 0)
' Display the encoded bytes.
' Each element is converted to an integer with Convert.ToInt32.
Console.WriteLine("Encoded bytes in hexadecimal ({0} bytes):" & vbCrLf, _
numberOfEncodedBytes)
ix = 0
Dim b As Byte
For Each b In encodedBytes
Console.Write("0x{0:X2} ", Convert.ToInt32(b))
ix += 1
If 0 = ix Mod 6 Then
Console.WriteLine()
End If
Next b
Console.Write(twoNewLines)
' --------------------------------------------------------------------------
' Decode the encoded bytes, yielding a reconstituted string.
Console.WriteLine("Decode the encoded bytes...")
decodedString = ae.GetString(encodedBytes)
' Display the input string and the decoded string for comparison.
Console.WriteLine("Input string: ""{0}""", inputString)
Console.WriteLine("Decoded string:""{0}""", decodedString)
End Sub
End Class
'
'This code example produces the following results:
'
'The name of the encoding is "us-ascii".
'
'Input string (3 characters): "X"
'Input string in hexadecimal: 0xAB 0x58 0xBB
'
'Encode the input string...
'Encoded bytes in hexadecimal (19 bytes):
'
'0x28 0x75 0x6E 0x6B 0x6E 0x6F
'0x77 0x6E 0x29 0x58 0x28 0x75
'0x6E 0x6B 0x6E 0x6F 0x77 0x6E
'0x29
'
'Decode the encoded bytes...
'Input string: "X"
'Decoded string:"(unknown)X(unknown)"
'
Commenti
In .NET Framework il GetEncoding metodo si basa sulla piattaforma sottostante per supportare la maggior parte delle tabelle codici. .NET Framework supporta tuttavia in modo nativo alcune codifiche. Per un elenco delle tabelle codici, vedere Elenco delle codifiche. In .NET Core il GetEncoding metodo restituisce le codifiche supportate in modo nativo da .NET Core. In entrambe le implementazioni di .NET è possibile chiamare il GetEncodings metodo per ottenere una matrice di EncodingInfo oggetti che contiene informazioni su tutte le codifiche disponibili.
Oltre alle codifiche disponibili in modo nativo in .NET Core o supportate intrinsecamente in una versione specifica della piattaforma di .NET Framework, il GetEncoding metodo restituisce eventuali codifiche aggiuntive rese disponibili registrando un EncodingProvider oggetto . Se la stessa codifica è stata registrata da più EncodingProvider oggetti, questo metodo restituisce l'ultimo oggetto registrato.
In .NET 5 e versioni successive il nome utf-7 della tabella codici non è supportato.
Annotazioni
Le tabelle codici ANSI possono essere diverse in computer diversi e possono cambiare in un singolo computer, causando il danneggiamento dei dati. Per i risultati più coerenti, è consigliabile usare una codifica Unicode, ad esempio UTF-8 (tabella codici 65001) o UTF-16, anziché una tabella codici specifica.
GetEncoding restituisce un'istanza memorizzata nella cache con le impostazioni predefinite. È consigliabile usare i costruttori delle classi derivate per ottenere un'istanza con impostazioni diverse. Ad esempio, la UTF32Encoding classe fornisce un costruttore che consente di abilitare il rilevamento degli errori.
Vedi anche
- EncoderFallback
- EncoderFallback
- GetEncodings()
- Come usare le classi di codifica dei caratteri in .NET