Encoding.GetString Método
Definição
Quando substituído em uma classe derivada, decodifica uma sequência de bytes em uma cadeia de caracteres.When overridden in a derived class, decodes a sequence of bytes into a string.
Sobrecargas
| GetString(Byte[]) |
Quando substituído em uma classe derivada, decodifica todos os bytes na matriz de bytes especificada em uma cadeia de caracteres.When overridden in a derived class, decodes all the bytes in the specified byte array into a string. |
| GetString(ReadOnlySpan<Byte>) |
Quando substituído em uma classe derivada, decodifica todos os bytes no intervalo de bytes especificado em uma cadeia de caracteres.When overridden in a derived class, decodes all the bytes in the specified byte span into a string. |
| GetString(Byte*, Int32) |
Quando substituído em uma classe derivada, decodifica um número especificado de bytes, começando em um endereço especificado em uma cadeia de caracteres.When overridden in a derived class, decodes a specified number of bytes starting at a specified address into a string. |
| GetString(Byte[], Int32, Int32) |
Quando substituído em uma classe derivada, decodifica uma sequência de bytes da matriz de bytes especificada em uma cadeia de caracteres.When overridden in a derived class, decodes a sequence of bytes from the specified byte array into a string. |
GetString(Byte[])
Quando substituído em uma classe derivada, decodifica todos os bytes na matriz de bytes especificada em uma cadeia de caracteres.When overridden in a derived class, decodes all the bytes in the specified byte array into a string.
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
Parâmetros
- bytes
- Byte[]
A matriz de bytes que contém a sequência de bytes a ser decodificada.The byte array containing the sequence of bytes to decode.
Retornos
Uma cadeia de caracteres que contém os resultados da decodificação da sequência de bytes especificada.A string that contains the results of decoding the specified sequence of bytes.
Exceções
A matriz de bytes contém pontos de código Unicode inválidos.The byte array contains invalid Unicode code points.
bytes é null.bytes is null.
Ocorreu um fallback (saiba mais em Codificação de caracteres no .NET)A fallback occurred (for more information, see Character Encoding in .NET)
-e--and-
DecoderFallback é definido como DecoderExceptionFallback.DecoderFallback is set to DecoderExceptionFallback.
Exemplos
O exemplo a seguir lê uma cadeia de caracteres codificada em UTF-8 de um arquivo binário representado por um FileStream objeto.The following example reads a UTF-8 encoded string from a binary file represented by a FileStream object. Para arquivos menores que 2.048 bytes, ele lê o conteúdo de todo o arquivo em uma matriz de bytes e chama o GetString(Byte[]) método para executar a decodificação.For files that are smaller than 2,048 bytes, it reads the contents of the entire file into a byte array and calls the GetString(Byte[]) method to perform the decoding. Para arquivos maiores, ele lê 2.048 bytes por vez em uma matriz de bytes, chama o Decoder.GetCharCount(Byte[], Int32, Int32) método para determinar quantos caracteres estão contidos na matriz e, em seguida, chama o Decoder.GetChars(Byte[], Int32, Int32, Char[], Int32) método para executar a decodificação.For larger files, it reads 2,048 bytes at a time into a byte array, calls the Decoder.GetCharCount(Byte[], Int32, Int32) method to determine how many characters are contained in the array, and then calls the Decoder.GetChars(Byte[], Int32, Int32, Char[], Int32) method to perform the decoding.
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.
O exemplo usa o texto a seguir, que deve ser salvo em um arquivo codificado em UTF-8 chamado Utf8Example.txt.The example uses the following text, which should be saved to a UTF-8 encoded file named 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.
Comentários
Se os dados a serem convertidos estiverem disponíveis somente em blocos sequenciais (como dados lidos de um fluxo) ou se a quantidade de dados for tão grande que precise ser dividida em blocos menores, você deverá usar o Decoder objeto retornado pelo GetDecoder método de uma classe derivada.If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the Decoder object returned by the GetDecoder method of a derived class.
Consulte a seção comentários do Encoding.GetChars tópico de referência para obter uma discussão de como decodificar técnicas e considerações.See the Remarks section of the Encoding.GetChars reference topic for a discussion of decoding techniques and considerations.
Observe que o comportamento preciso do GetString método para uma implementação específica Encoding depende da estratégia de fallback definida para esse Encoding objeto.Note that the precise behavior of the GetString method for a particular Encoding implementation depends on the fallback strategy defined for that Encoding object. Para obter mais informações, consulte a seção "escolhendo uma estratégia de fallback" do tópico codificação de caracteres no .net .For more information, see the "Choosing a Fallback Strategy" section of the Character Encoding in .NET topic.
Confira também
Aplica-se a
GetString(ReadOnlySpan<Byte>)
Quando substituído em uma classe derivada, decodifica todos os bytes no intervalo de bytes especificado em uma cadeia de caracteres.When overridden in a derived class, decodes all the bytes in the specified byte span into a string.
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
Parâmetros
- bytes
- ReadOnlySpan<Byte>
Um intervalo de bytes somente leitura a ser decodificado para uma cadeia de caracteres Unicode.A read-only byte span to decode to a Unicode string.
Retornos
Uma cadeia de caracteres que contém os bytes decodificados do intervalo de somente leitura fornecido.A string that contains the decoded bytes from the provided read-only span.
Comentários
O GetString método foi projetado para otimizar o desempenho.The GetString method is designed to optimize performance. Em vez de criar uma matriz de bytes gerenciado e, em seguida, decodificá-la, você pode chamar esse método sem precisar criar objetos intermediários.Instead of creating a managed byte array and then decoding it, you can instead call this method without having to create any intermediate objects.
Se os dados a serem convertidos estiverem disponíveis somente em blocos sequenciais (como dados lidos de um fluxo) ou se a quantidade de dados for tão grande que precise ser dividida em blocos menores, você deverá usar o Decoder objeto retornado pelo GetDecoder método de uma classe derivada.If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the Decoder object returned by the GetDecoder method of a derived class.
Consulte a seção comentários do Encoding.GetChars tópico de referência para obter uma discussão de como decodificar técnicas e considerações.See the Remarks section of the Encoding.GetChars reference topic for a discussion of decoding techniques and considerations.
Observe que o comportamento preciso do GetString método para uma implementação específica Encoding depende da estratégia de fallback definida para esse Encoding objeto.Note that the precise behavior of the GetString method for a particular Encoding implementation depends on the fallback strategy defined for that Encoding object. Para obter mais informações, consulte a seção "escolhendo uma estratégia de fallback" do tópico codificação de caracteres no .net .For more information, see the "Choosing a Fallback Strategy" section of the Character Encoding in .NET topic.
Aplica-se a
GetString(Byte*, Int32)
Importante
Esta API não está em conformidade com CLS.
Quando substituído em uma classe derivada, decodifica um número especificado de bytes, começando em um endereço especificado em uma cadeia de caracteres.When overridden in a derived class, decodes a specified number of bytes starting at a specified address into a string.
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)]
public string GetString (byte* bytes, int byteCount);
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)>]
[<System.Security.SecurityCritical>]
member this.GetString : nativeptr<byte> * int -> string
[<System.CLSCompliant(false)>]
member this.GetString : nativeptr<byte> * int -> string
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
Parâmetros
- bytes
- Byte*
Um ponteiro para uma matriz de bytes.A pointer to a byte array.
- byteCount
- Int32
O número de bytes a serem decodificados.The number of bytes to decode.
Retornos
Uma cadeia de caracteres que contém os resultados da decodificação da sequência de bytes especificada.A string that contains the results of decoding the specified sequence of bytes.
- Atributos
Exceções
O bytes é um ponteiro nulo.bytes is a null pointer.
byteCount é menor que zero.byteCount is less than zero.
Ocorreu um fallback (confira Codificação de caracteres no .NET para obter uma explicação completa)A fallback occurred (see Character Encoding in .NET) for a complete explanation)
-e--and-
DecoderFallback é definido como DecoderExceptionFallback.DecoderFallback is set to DecoderExceptionFallback.
Comentários
O GetString método foi projetado para otimizar o desempenho quando você tem um ponteiro nativo para uma matriz de bytes.The GetString method is designed to optimize performance when you have a native pointer to a byte array. Em vez de criar uma matriz de bytes gerenciado e, em seguida, decodificá-la, você pode chamar esse método sem precisar criar objetos intermediários.Instead of creating a managed byte array and then decoding it, you can instead call this method without having to create any intermediate objects.
Se os dados a serem convertidos estiverem disponíveis somente em blocos sequenciais (como dados lidos de um fluxo) ou se a quantidade de dados for tão grande que precise ser dividida em blocos menores, você deverá usar o Decoder objeto retornado pelo GetDecoder método de uma classe derivada.If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the Decoder object returned by the GetDecoder method of a derived class.
Consulte a seção comentários do Encoding.GetChars tópico de referência para obter uma discussão de como decodificar técnicas e considerações.See the Remarks section of the Encoding.GetChars reference topic for a discussion of decoding techniques and considerations.
Observe que o comportamento preciso do GetString método para uma implementação específica Encoding depende da estratégia de fallback definida para esse Encoding objeto.Note that the precise behavior of the GetString method for a particular Encoding implementation depends on the fallback strategy defined for that Encoding object. Para obter mais informações, consulte a seção "escolhendo uma estratégia de fallback" do tópico codificação de caracteres no .net .For more information, see the "Choosing a Fallback Strategy" section of the Character Encoding in .NET topic.
Confira também
Aplica-se a
GetString(Byte[], Int32, Int32)
Quando substituído em uma classe derivada, decodifica uma sequência de bytes da matriz de bytes especificada em uma cadeia de caracteres.When overridden in a derived class, decodes a sequence of bytes from the specified byte array into a string.
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
Parâmetros
- bytes
- Byte[]
A matriz de bytes que contém a sequência de bytes a ser decodificada.The byte array containing the sequence of bytes to decode.
- index
- Int32
O índice do primeiro byte a ser decodificado.The index of the first byte to decode.
- count
- Int32
O número de bytes a serem decodificados.The number of bytes to decode.
Retornos
Uma cadeia de caracteres que contém os resultados da decodificação da sequência de bytes especificada.A string that contains the results of decoding the specified sequence of bytes.
Exceções
A matriz de bytes contém pontos de código Unicode inválidos.The byte array contains invalid Unicode code points.
bytes é null.bytes is null.
index ou count é menor que zero.index or count is less than zero.
- ou --or-
index e count não denotam um intervalo válido em bytes.index and count do not denote a valid range in bytes.
Ocorreu um fallback (saiba mais em Codificação de caracteres no .NET)A fallback occurred (for more information, see Character Encoding in .NET)
-e--and-
DecoderFallback é definido como DecoderExceptionFallback.DecoderFallback is set to DecoderExceptionFallback.
Exemplos
O exemplo a seguir lê uma cadeia de caracteres codificada em UTF-8 de um arquivo binário representado por um FileStream objeto.The following example reads a UTF-8 encoded string from a binary file that is represented by a FileStream object. Para arquivos menores que 2.048 bytes, ele lê o conteúdo de todo o arquivo em uma matriz de bytes e chama o GetString(Byte[], Int32, Int32) método para executar a decodificação.For files that are smaller than 2,048 bytes, it reads the contents of the entire file into a byte array and calls the GetString(Byte[], Int32, Int32) method to perform the decoding. Para arquivos maiores, ele lê 2.048 bytes por vez em uma matriz de bytes, chama o Decoder.GetCharCount(Byte[], Int32, Int32) método para determinar quantos caracteres estão contidos na matriz e, em seguida, chama o Decoder.GetChars(Byte[], Int32, Int32, Char[], Int32) método para executar a decodificação.For larger files, it reads 2,048 bytes at a time into a byte array, calls the Decoder.GetCharCount(Byte[], Int32, Int32) method to determine how many characters are contained in the array, and then calls the Decoder.GetChars(Byte[], Int32, Int32, Char[], Int32) method to perform the decoding.
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.
O exemplo usa o texto a seguir, que deve ser salvo em um arquivo codificado em UTF-8 chamado Utf8Example.txt.The example uses the following text, which should be saved to a UTF-8 encoded file named 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.
Comentários
Se os dados a serem convertidos estiverem disponíveis somente em blocos sequenciais (como dados lidos de um fluxo) ou se a quantidade de dados for tão grande que precise ser dividida em blocos menores, você deverá usar o Decoder ou o Encoder fornecido pelo GetDecoder método ou pelo GetEncoder método, respectivamente, de uma classe derivada.If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively, of a derived class.
Consulte a seção comentários do Encoding.GetChars tópico de referência para obter uma discussão de como decodificar técnicas e considerações.See the Remarks section of the Encoding.GetChars reference topic for a discussion of decoding techniques and considerations.