Encoding.GetString 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.
In caso di override in una classe derivata, decodifica una sequenza di byte in una stringa.
Overload
| Nome | Descrizione |
|---|---|
| GetString(Byte[], Int32, Int32) |
In caso di override in una classe derivata, decodifica una sequenza di byte dalla matrice di byte specificata in una stringa. |
| GetString(Byte*, Int32) |
Quando sottoposto a override in una classe derivata, decodifica un numero specificato di byte a partire da un indirizzo specificato in una stringa. |
| GetString(Byte[]) |
In caso di override in una classe derivata, decodifica tutti i byte nella matrice di byte specificata in una stringa. |
| GetString(ReadOnlySpan<Byte>) |
Quando sottoposto a override in una classe derivata, decodifica tutti i byte nell'intervallo di byte specificato in una stringa. |
GetString(Byte[], Int32, Int32)
In caso di override in una classe derivata, decodifica una sequenza di byte dalla matrice di byte specificata in una stringa.
public:
virtual System::String ^ GetString(cli::array <System::Byte> ^ bytes, int index, int count);
public virtual string GetString(byte[] bytes, int index, int count);
abstract member GetString : byte[] * int * int -> string
override this.GetString : byte[] * int * int -> string
Public Overridable Function GetString (bytes As Byte(), index As Integer, count As Integer) As String
Parametri
- bytes
- Byte[]
Matrice di byte contenente la sequenza di byte da decodificare.
- index
- Int32
Indice del primo byte da decodificare.
- count
- Int32
Numero di byte da decodificare.
Valori restituiti
Stringa che contiene i risultati della decodifica della sequenza di byte specificata.
Eccezioni
La matrice di byte contiene punti di codice Unicode non validi.
bytes è null.
index o count è minore di zero.
oppure
index e count non indicano un intervallo valido in bytes.
Si è verificato un fallback (per altre informazioni, vedere Codifica dei caratteri in .NET)
-e-
DecoderFallback è impostato su DecoderExceptionFallback.
Esempio
Nell'esempio seguente viene letta una stringa con codifica UTF-8 da un file binario rappresentato da un FileStream oggetto . Per i file di dimensioni inferiori a 2.048 byte, legge il contenuto dell'intero file in una matrice di byte e chiama il GetString(Byte[], Int32, Int32) metodo per eseguire la decodifica. Per i file di dimensioni maggiori, legge 2.048 byte alla volta in una matrice di byte, chiama il Decoder.GetCharCount(Byte[], Int32, Int32) metodo per determinare il numero di caratteri contenuti nella matrice e quindi chiama il Decoder.GetChars(Byte[], Int32, Int32, Char[], Int32) metodo per eseguire la decodifica.
using System;
using System.IO;
using System.Text;
public class Example
{
const int MAX_BUFFER_SIZE = 2048;
static Encoding enc8 = Encoding.UTF8;
static byte[] bytes = new byte[MAX_BUFFER_SIZE];
public static void Main()
{
FileStream fStream = new FileStream(@".\Utf8Example.txt", FileMode.Open);
string contents = null;
// If file size is small, read in a single operation.
if (fStream.Length <= MAX_BUFFER_SIZE) {
int bytesRead = fStream.Read(bytes, 0, bytes.Length);
contents = enc8.GetString(bytes, 0, bytesRead);
}
// If file size exceeds buffer size, perform multiple reads.
else {
contents = ReadFromBuffer(fStream);
}
fStream.Close();
Console.WriteLine(contents);
}
private static string ReadFromBuffer(FileStream fStream)
{
string output = String.Empty;
Decoder decoder8 = enc8.GetDecoder();
while (fStream.Position < fStream.Length) {
int nBytes = fStream.Read(bytes, 0, bytes.Length);
int nChars = decoder8.GetCharCount(bytes, 0, nBytes);
char[] chars = new char[nChars];
nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0);
output += new String(chars, 0, nChars);
}
return output;
}
}
// The example displays the following output:
// This is a UTF-8-encoded file that contains primarily Latin text, although it
// does list the first twelve letters of the Russian (Cyrillic) alphabet:
//
// А б в г д е ё ж з и й к
//
// The goal is to save this file, then open and decode it as a binary stream.
Imports System.IO
Imports System.Text
Module Example
Const MAX_BUFFER_SIZE As Integer = 2048
Dim enc8 As Encoding = Encoding.UTF8
Dim bytes(MAX_BUFFER_SIZE -1) As Byte
Public Sub Main()
Dim fStream As New FileStream(".\Utf8Example.txt", FileMode.Open)
Dim contents As String = Nothing
' If file size is small, read in a single operation.
If fStream.Length <= MAX_BUFFER_SIZE Then
Dim bytesRead As Integer = fStream.Read(bytes, 0, bytes.Length)
contents = enc8.GetString(bytes, 0, bytesRead)
' If file size exceeds buffer size, perform multiple reads.
Else
contents = ReadFromBuffer(fStream)
End If
fStream.Close()
Console.WriteLine(contents)
End Sub
Private Function ReadFromBuffer(fStream As FileStream) As String
Dim bytes(MAX_BUFFER_SIZE) As Byte
Dim output As String = String.Empty
Dim decoder8 As Decoder = enc8.GetDecoder()
Do While fStream.Position < fStream.Length
Dim nBytes As Integer = fStream.Read(bytes, 0, bytes.Length)
Dim nChars As Integer = decoder8.GetCharCount(bytes, 0, nBytes)
Dim chars(nChars - 1) As Char
nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0)
output += New String(chars, 0, nChars)
Loop
Return output
End Function
End Module
' The example displays the following output:
' This is a UTF-8-encoded file that contains primarily Latin text, although it
' does list the first twelve letters of the Russian (Cyrillic) alphabet:
'
' А б в г д е ё ж з и й к
'
' The goal is to save this file, then open and decode it as a binary stream.
Nell'esempio viene usato il testo seguente, che deve essere salvato in un file con codifica UTF-8 denominato Utf8Example.txt.
This is a UTF-8-encoded file that contains primarily Latin text, although it
does list the first twelve letters of the Russian (Cyrillic) alphabet:
А б в г д е ё ж з и й к
The goal is to save this file, then open and decode it as a binary stream.
Commenti
Se i dati da convertire sono disponibili solo in blocchi sequenziali (ad esempio i dati letti da un flusso) o se la quantità di dati è così grande che deve essere suddivisa in blocchi più piccoli, è necessario usare rispettivamente l'oggetto Decoder o fornito Encoder dal GetDecoder metodo o dal GetEncoder metodo di una classe derivata.
Per una descrizione delle tecniche e delle considerazioni sulla decodifica, vedere la sezione Osservazioni dell'argomento Encoding.GetChars di riferimento.
Vedi anche
Si applica a
GetString(Byte*, Int32)
Importante
Questa API non è conforme a CLS.
Quando sottoposto a override in una classe derivata, decodifica un numero specificato di byte a partire da un indirizzo specificato in una stringa.
public:
System::String ^ GetString(System::Byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
public string GetString(byte* bytes, int byteCount);
[System.CLSCompliant(false)]
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(false)]
public string GetString(byte* bytes, int byteCount);
[System.CLSCompliant(false)]
public string GetString(byte* bytes, int byteCount);
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
member this.GetString : nativeptr<byte> * int -> string
[<System.CLSCompliant(false)>]
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(false)>]
member this.GetString : nativeptr<byte> * int -> string
[<System.CLSCompliant(false)>]
member this.GetString : nativeptr<byte> * int -> string
Parametri
- bytes
- Byte*
Puntatore a una matrice di byte.
- byteCount
- Int32
Numero di byte da decodificare.
Valori restituiti
Stringa che contiene i risultati della decodifica della sequenza di byte specificata.
- Attributi
Eccezioni
bytes è un puntatore Null.
byteCount è minore di zero.
Si è verificato un fallback (vedere Caracter Encoding in .NET per una spiegazione completa)
-e-
DecoderFallback è impostato su DecoderExceptionFallback.
Commenti
Il GetString metodo è progettato per ottimizzare le prestazioni quando si dispone di un puntatore nativo a una matrice di byte. Anziché creare una matrice di byte gestita e decodificarla, è invece possibile chiamare questo metodo senza dover creare oggetti intermedi.
Se i dati da convertire sono disponibili solo in blocchi sequenziali (ad esempio i dati letti da un flusso) o se la quantità di dati è così grande che deve essere divisa in blocchi più piccoli, è necessario usare l'oggetto Decoder restituito dal GetDecoder metodo di una classe derivata.
Per una descrizione delle tecniche e delle considerazioni sulla decodifica, vedere la sezione Osservazioni dell'argomento Encoding.GetChars di riferimento.
Si noti che il comportamento preciso del GetString metodo per una particolare Encoding implementazione dipende dalla strategia di fallback definita per tale Encoding oggetto. Per altre informazioni, vedere la sezione "Scelta di una strategia di fallback" dell'argomento Caracter Encoding in .NET.
Vedi anche
Si applica a
GetString(Byte[])
In caso di override in una classe derivata, decodifica tutti i byte nella matrice di byte specificata in una stringa.
public:
virtual System::String ^ GetString(cli::array <System::Byte> ^ bytes);
public virtual string GetString(byte[] bytes);
abstract member GetString : byte[] -> string
override this.GetString : byte[] -> string
Public Overridable Function GetString (bytes As Byte()) As String
Parametri
- bytes
- Byte[]
Matrice di byte contenente la sequenza di byte da decodificare.
Valori restituiti
Stringa che contiene i risultati della decodifica della sequenza di byte specificata.
Eccezioni
La matrice di byte contiene punti di codice Unicode non validi.
bytes è null.
Si è verificato un fallback (per altre informazioni, vedere Codifica dei caratteri in .NET)
-e-
DecoderFallback è impostato su DecoderExceptionFallback.
Esempio
Nell'esempio seguente viene letta una stringa con codifica UTF-8 da un file binario rappresentato da un FileStream oggetto . Per i file di dimensioni inferiori a 2.048 byte, legge il contenuto dell'intero file in una matrice di byte e chiama il GetString(Byte[]) metodo per eseguire la decodifica. Per i file di dimensioni maggiori, legge 2.048 byte alla volta in una matrice di byte, chiama il Decoder.GetCharCount(Byte[], Int32, Int32) metodo per determinare il numero di caratteri contenuti nella matrice e quindi chiama il Decoder.GetChars(Byte[], Int32, Int32, Char[], Int32) metodo per eseguire la decodifica.
using System;
using System.IO;
using System.Text;
public class Example
{
const int MAX_BUFFER_SIZE = 2048;
static Encoding enc8 = Encoding.UTF8;
public static void Main()
{
FileStream fStream = new FileStream(@".\Utf8Example.txt", FileMode.Open);
string contents = null;
// If file size is small, read in a single operation.
if (fStream.Length <= MAX_BUFFER_SIZE) {
Byte[] bytes = new Byte[fStream.Length];
fStream.Read(bytes, 0, bytes.Length);
contents = enc8.GetString(bytes);
}
// If file size exceeds buffer size, perform multiple reads.
else {
contents = ReadFromBuffer(fStream);
}
fStream.Close();
Console.WriteLine(contents);
}
private static string ReadFromBuffer(FileStream fStream)
{
Byte[] bytes = new Byte[MAX_BUFFER_SIZE];
string output = String.Empty;
Decoder decoder8 = enc8.GetDecoder();
while (fStream.Position < fStream.Length) {
int nBytes = fStream.Read(bytes, 0, bytes.Length);
int nChars = decoder8.GetCharCount(bytes, 0, nBytes);
char[] chars = new char[nChars];
nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0);
output += new String(chars, 0, nChars);
}
return output;
}
}
// The example displays the following output:
// This is a UTF-8-encoded file that contains primarily Latin text, although it
// does list the first twelve letters of the Russian (Cyrillic) alphabet:
//
// А б в г д е ё ж з и й к
//
// The goal is to save this file, then open and decode it as a binary stream.
Imports System.IO
Imports System.Text
Module Example
Const MAX_BUFFER_SIZE As Integer = 2048
Dim enc8 As Encoding = Encoding.UTF8
Public Sub Main()
Dim fStream As New FileStream(".\Utf8Example.txt", FileMode.Open)
Dim contents As String = Nothing
' If file size is small, read in a single operation.
If fStream.Length <= MAX_BUFFER_SIZE Then
Dim bytes(CInt(fStream.Length) - 1) As Byte
fStream.Read(bytes, 0, bytes.Length)
contents = enc8.GetString(bytes)
' If file size exceeds buffer size, perform multiple reads.
Else
contents = ReadFromBuffer(fStream)
End If
fStream.Close()
Console.WriteLine(contents)
End Sub
Private Function ReadFromBuffer(fStream As FileStream) As String
Dim bytes(MAX_BUFFER_SIZE) As Byte
Dim output As String = String.Empty
Dim decoder8 As Decoder = enc8.GetDecoder()
Do While fStream.Position < fStream.Length
Dim nBytes As Integer = fStream.Read(bytes, 0, bytes.Length)
Dim nChars As Integer = decoder8.GetCharCount(bytes, 0, nBytes)
Dim chars(nChars - 1) As Char
nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0)
output += New String(chars, 0, nChars)
Loop
Return output
End Function
End Module
' The example displays the following output:
' This is a UTF-8-encoded file that contains primarily Latin text, although it
' does list the first twelve letters of the Russian (Cyrillic) alphabet:
'
' ? ? ? ? ? ? ? ? ? ? ? ?
'
' The goal is to save this file, then open and decode it as a binary stream.
Nell'esempio viene usato il testo seguente, che deve essere salvato in un file con codifica UTF-8 denominato Utf8Example.txt.
This is a UTF-8-encoded file that contains primarily Latin text, although it
does list the first twelve letters of the Russian (Cyrillic) alphabet:
А б в г д е ё ж з и й к
The goal is to save this file, then open and decode it as a binary stream.
Commenti
Se i dati da convertire sono disponibili solo in blocchi sequenziali (ad esempio i dati letti da un flusso) o se la quantità di dati è così grande che deve essere divisa in blocchi più piccoli, è necessario usare l'oggetto Decoder restituito dal GetDecoder metodo di una classe derivata.
Per una descrizione delle tecniche e delle considerazioni sulla decodifica, vedere la sezione Osservazioni dell'argomento Encoding.GetChars di riferimento.
Si noti che il comportamento preciso del GetString metodo per una particolare Encoding implementazione dipende dalla strategia di fallback definita per tale Encoding oggetto. Per altre informazioni, vedere la sezione "Scelta di una strategia di fallback" dell'argomento Caracter Encoding in .NET.
Vedi anche
Si applica a
GetString(ReadOnlySpan<Byte>)
Quando sottoposto a override in una classe derivata, decodifica tutti i byte nell'intervallo di byte specificato in una stringa.
public:
System::String ^ GetString(ReadOnlySpan<System::Byte> bytes);
public string GetString(ReadOnlySpan<byte> bytes);
member this.GetString : ReadOnlySpan<byte> -> string
Public Function GetString (bytes As ReadOnlySpan(Of Byte)) As String
Parametri
- bytes
- ReadOnlySpan<Byte>
Intervallo di byte di sola lettura da decodificare in una stringa Unicode.
Valori restituiti
Stringa che contiene i byte decodificati dall'intervallo di sola lettura specificato.
Commenti
Il GetString metodo è progettato per ottimizzare le prestazioni. Anziché creare una matrice di byte gestita e decodificarla, è invece possibile chiamare questo metodo senza dover creare oggetti intermedi.
Se i dati da convertire sono disponibili solo in blocchi sequenziali (ad esempio i dati letti da un flusso) o se la quantità di dati è così grande che deve essere divisa in blocchi più piccoli, è necessario usare l'oggetto Decoder restituito dal GetDecoder metodo di una classe derivata.
Per una descrizione delle tecniche e delle considerazioni sulla decodifica, vedere la sezione Osservazioni dell'argomento Encoding.GetChars di riferimento.
Si noti che il comportamento preciso del GetString metodo per una particolare Encoding implementazione dipende dalla strategia di fallback definita per tale Encoding oggetto. Per altre informazioni, vedere la sezione "Scelta di una strategia di fallback" dell'argomento Caracter Encoding in .NET.