Encoder.Convert Método

Definição

Converte um buffer ou uma matriz de caracteres Unicode em uma sequência de bytes codificados.

Sobrecargas

Convert(ReadOnlySpan<Char>, Span<Byte>, Boolean, Int32, Int32, Boolean)

Converte um intervalo de caracteres Unicode em uma sequência de bytes codificados e armazena o resultado em outro buffer.

Convert(Char*, Int32, Byte*, Int32, Boolean, Int32, Int32, Boolean)

Converte um buffer de caracteres Unicode em uma sequência de bytes codificados e armazena o resultado em outro buffer.

Convert(Char[], Int32, Int32, Byte[], Int32, Int32, Boolean, Int32, Int32, Boolean)

Converte uma matriz de caracteres Unicode em uma sequência de bytes codificados e armazena o resultado em uma matriz de bytes.

Convert(ReadOnlySpan<Char>, Span<Byte>, Boolean, Int32, Int32, Boolean)

Converte um intervalo de caracteres Unicode em uma sequência de bytes codificados e armazena o resultado em outro buffer.

public:
 virtual void Convert(ReadOnlySpan<char> chars, Span<System::Byte> bytes, bool flush, [Runtime::InteropServices::Out] int % charsUsed, [Runtime::InteropServices::Out] int % bytesUsed, [Runtime::InteropServices::Out] bool % completed);
public virtual void Convert (ReadOnlySpan<char> chars, Span<byte> bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed);
abstract member Convert : ReadOnlySpan<char> * Span<byte> * bool * int * int * bool -> unit
override this.Convert : ReadOnlySpan<char> * Span<byte> * bool * int * int * bool -> unit
Public Overridable Sub Convert (chars As ReadOnlySpan(Of Char), bytes As Span(Of Byte), flush As Boolean, ByRef charsUsed As Integer, ByRef bytesUsed As Integer, ByRef completed As Boolean)

Parâmetros

chars
ReadOnlySpan<Char>

O intervalo de caracteres codificados em UTF-16 a serem convertidos.

bytes
Span<Byte>

O buffer de intervalo para armazenar os bytes convertidos.

flush
Boolean

true para indicar que mais nenhum dado deve ser convertido; caso contrário, false.

charsUsed
Int32

Quando este método retorna, contém o número de caracteres do chars que foram usados na conversão. Este parâmetro é passado não inicializado.

bytesUsed
Int32

Quando este método retorna, ele contém o número de bytes que foram usados na conversão. Este parâmetro é passado não inicializado.

completed
Boolean

Quando este método for retornado, ele conterá true se todos os caracteres em chars tiverem sido convertidos; caso contrário, false. Este parâmetro é passado não inicializado.

Comentários

Lembre-se de Encoder que o objeto salva o estado entre chamadas para Convert . Quando o aplicativo é feito com um fluxo de dados, ele deve definir o parâmetro como para garantir que as informações flush true de estado são liberados. Com essa configuração, o codificador ignora bytes inválidos no final do bloco de dados e limpa o buffer interno. Todos os dados processados restantes que fazem parte de uma unidade lógica, como o substituto alto de um par substituto, são convertidos de acordo com as configurações de fallback atuais.

O método foi projetado para ser usado em um loop para codificar uma quantidade arbitrária de entrada, como dados lidos Convert de um arquivo ou fluxo. Ele armazena a saída da operação de codificação em um buffer de tamanho fixo. GetBytes lançará uma exceção se o buffer de saída não for grande o suficiente, mas preencherá o máximo de espaço possível e retornará os Convert caracteres lidos e os bytes gravados. Consulte também o Encoding.GetBytes tópico para obter mais comentários.

O completed parâmetro de saída indica se todos os dados no buffer de entrada foram convertidos e armazenados no buffer de saída. Esse parâmetro será definido como se o número de caracteres especificado pelo parâmetro não puder ser convertido sem exceder o número de false bytes especificado pelo parâmetro charCount byteCount . Nessa situação, o aplicativo deve usar o conteúdo do buffer de saída ou fornecer um novo buffer de saída, incrementar o parâmetro pelo número de caracteres especificados pelo parâmetro e, em seguida, chamar o método novamente para processar a entrada chars charsUsed Convert restante.

O parâmetro também pode ser definido como , mesmo que o parâmetro e o comprimento completed do intervalo false charsUsed 'char' sejam iguais. Essa situação ocorrerá se ainda houver dados no Encoder objeto que não foram armazenados no chars buffer.

Aplica-se a

Convert(Char*, Int32, Byte*, Int32, Boolean, Int32, Int32, Boolean)

Importante

Esta API não está em conformidade com CLS.

Alternativa em conformidade com CLS
System.Text.Encoder.Convert(Char[], Int32, Int32, Byte[], Int32, Int32, Boolean, Int32, Int32, Boolean)

Converte um buffer de caracteres Unicode em uma sequência de bytes codificados e armazena o resultado em outro buffer.

public:
 virtual void Convert(char* chars, int charCount, System::Byte* bytes, int byteCount, bool flush, [Runtime::InteropServices::Out] int % charsUsed, [Runtime::InteropServices::Out] int % bytesUsed, [Runtime::InteropServices::Out] bool % completed);
[System.CLSCompliant(false)]
public virtual void Convert (char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed);
public virtual void Convert (char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed);
[System.CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
public virtual void Convert (char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed);
[System.CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(false)]
[System.Security.SecurityCritical]
public virtual void Convert (char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed);
[<System.CLSCompliant(false)>]
abstract member Convert : nativeptr<char> * int * nativeptr<byte> * int * bool * int * int * bool -> unit
override this.Convert : nativeptr<char> * int * nativeptr<byte> * int * bool * int * int * bool -> unit
abstract member Convert : nativeptr<char> * int * nativeptr<byte> * int * bool * int * int * bool -> unit
override this.Convert : nativeptr<char> * int * nativeptr<byte> * int * bool * int * int * bool -> unit
[<System.CLSCompliant(false)>]
[<System.Runtime.InteropServices.ComVisible(false)>]
abstract member Convert : nativeptr<char> * int * nativeptr<byte> * int * bool * int * int * bool -> unit
override this.Convert : nativeptr<char> * int * nativeptr<byte> * int * bool * int * int * bool -> unit
[<System.CLSCompliant(false)>]
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Security.SecurityCritical>]
abstract member Convert : nativeptr<char> * int * nativeptr<byte> * int * bool * int * int * bool -> unit
override this.Convert : nativeptr<char> * int * nativeptr<byte> * int * bool * int * int * bool -> unit

Parâmetros

chars
Char*

O endereço de uma cadeia de caracteres codificados em UTF-16 para converter.

charCount
Int32

O número de caracteres em chars a converter.

bytes
Byte*

O endereço de um buffer para armazenar os bytes convertidos.

byteCount
Int32

O número máximo de elementos em bytes a usar na conversão.

flush
Boolean

true para indicar que mais nenhum dado deve ser convertido; caso contrário, false.

charsUsed
Int32

Quando este método retorna, contém o número de caracteres do chars que foram usados na conversão. Este parâmetro é passado não inicializado.

bytesUsed
Int32

Quando este método retorna, ele contém o número de bytes que foram usados na conversão. Este parâmetro é passado não inicializado.

completed
Boolean

Quando este método retorna, contém true se todos os caracteres especificados por charCount foram convertidos; caso contrário, false. Este parâmetro é passado não inicializado.

Atributos

Exceções

chars ou bytes é null (Nothing).

charCount ou byteCount é menor que zero.

O buffer de saída é muito pequeno para conter qualquer entrada convertida. O buffer de saída deve ser maior ou igual ao tamanho indicado pelo método GetByteCount.

Ocorreu um fallback (saiba mais em Codificação de caracteres no .NET)

-e-

Fallback é definido como EncoderExceptionFallback.

Comentários

Lembre-se de Encoder que o objeto salva o estado entre chamadas para Convert . Quando o aplicativo é feito com um fluxo de dados, ele deve definir o parâmetro como para garantir que as informações flush true de estado são liberados. Com essa configuração, o codificador ignora bytes inválidos no final do bloco de dados e limpa o buffer interno. Todos os dados processados restantes que fazem parte de uma unidade lógica, como o substituto alto de um par substituto, são convertidos de acordo com as configurações de fallback atuais.

O método foi projetado para ser usado em um loop para codificar uma quantidade arbitrária de entrada, como dados lidos Convert de um arquivo ou fluxo. Ele armazena a saída da operação de codificação em um buffer de tamanho fixo. GetBytes lançará uma exceção se o buffer de saída não for grande o suficiente, mas preencherá o máximo de espaço possível e retornará os Convert caracteres lidos e os bytes gravados. Consulte também o Encoding.GetBytes tópico para obter mais comentários.

O completed parâmetro de saída indica se todos os dados no buffer de entrada foram convertidos e armazenados no buffer de saída. Esse parâmetro será definido como se o número de caracteres especificado pelo parâmetro não puder ser convertido sem exceder o número de false bytes especificado pelo parâmetro charCount byteCount . Nessa situação, o aplicativo deve usar o conteúdo do buffer de saída ou fornecer um novo buffer de saída, incrementar o parâmetro pelo número de caracteres especificados pelo parâmetro e, em seguida, chamar o método novamente para processar a entrada chars charsUsed Convert restante.

O completed parâmetro também pode ser definido como , mesmo que os false charsUsed charCount parâmetros e sejam iguais. Essa situação ocorrerá se ainda houver dados no Encoder objeto que não foram armazenados no chars buffer.

Aplica-se a

Convert(Char[], Int32, Int32, Byte[], Int32, Int32, Boolean, Int32, Int32, Boolean)

Converte uma matriz de caracteres Unicode em uma sequência de bytes codificados e armazena o resultado em uma matriz de bytes.

public:
 virtual void Convert(cli::array <char> ^ chars, int charIndex, int charCount, cli::array <System::Byte> ^ bytes, int byteIndex, int byteCount, bool flush, [Runtime::InteropServices::Out] int % charsUsed, [Runtime::InteropServices::Out] int % bytesUsed, [Runtime::InteropServices::Out] bool % completed);
public virtual void Convert (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed);
[System.Runtime.InteropServices.ComVisible(false)]
public virtual void Convert (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed);
abstract member Convert : char[] * int * int * byte[] * int * int * bool * int * int * bool -> unit
override this.Convert : char[] * int * int * byte[] * int * int * bool * int * int * bool -> unit
[<System.Runtime.InteropServices.ComVisible(false)>]
abstract member Convert : char[] * int * int * byte[] * int * int * bool * int * int * bool -> unit
override this.Convert : char[] * int * int * byte[] * int * int * bool * int * int * bool -> unit
Public Overridable Sub Convert (chars As Char(), charIndex As Integer, charCount As Integer, bytes As Byte(), byteIndex As Integer, byteCount As Integer, flush As Boolean, ByRef charsUsed As Integer, ByRef bytesUsed As Integer, ByRef completed As Boolean)

Parâmetros

chars
Char[]

Uma matriz de caracteres a ser convertida.

charIndex
Int32

O primeiro elemento de chars a ser convertido.

charCount
Int32

O número de elementos de chars a serem convertidos.

bytes
Byte[]

Uma matriz em que os bytes convertidos são armazenados.

byteIndex
Int32

O primeiro elemento de bytes em que os dados são armazenados.

byteCount
Int32

O número máximo de elementos de bytes a serem usados na conversão.

flush
Boolean

true para indicar que mais nenhum dado deve ser convertido; caso contrário, false.

charsUsed
Int32

Quando este método retorna, contém o número de caracteres do chars que foram usados na conversão. Este parâmetro é passado não inicializado.

bytesUsed
Int32

Quando este método retorna, ele contém o número de bytes que foram produzidos pela conversão. Este parâmetro é passado não inicializado.

completed
Boolean

Quando este método retorna, contém true se todos os caracteres especificados por charCount foram convertidos; caso contrário, false. Este parâmetro é passado não inicializado.

Atributos

Exceções

chars ou bytes é null (Nothing).

charIndex, charCount, byteIndex ou byteCount é menor que zero.

  • ou -

O tamanho de chars - charIndex é menor que charCount.

  • ou -

O tamanho de bytes - byteIndex é menor que byteCount.

O buffer de saída é muito pequeno para conter qualquer entrada convertida. O buffer de saída deve ser maior ou igual ao tamanho indicado pelo método GetByteCount.

Ocorreu um fallback (saiba mais em Codificação de caracteres no .NET)

-e-

Fallback é definido como EncoderExceptionFallback.

Exemplos

O exemplo a seguir usa o método para converter um arquivo de caracteres UTF-16 em UTF-8 e, em seguida, usa o método para converter os caracteres Convert Convert UTF-8 novamente em caracteres UTF-16.

// This code example demonstrates the Encoder.Convert() and Decoder.Convert methods.
// This example uses files for input and output, but any source that can be expressed
// as a stream can be used instead.

    using System;
    using System.Text;
    using System.IO;

    public class Sample
    {
    static void Main(string[] args)
        {
// Create a large file of UTF-16 encoded Unicode characters. The file is named Example.txt,
// and is used as input to the Encoder.Convert() method.

            CreateTestFile("Example.txt");

// Using an input file of UTF-16 encoded characters named Example.txt, create an output file
// of UTF-8 encoded bytes named UTF8.txt.

            EncoderConvert("Example.txt", "UTF8.txt", Encoding.UTF8);

// Using an input file of UTF-8 encoded bytes named UTF8.txt, create an output file
// of UTF-16 encoded characters named UTF16.txt.

            DecoderConvert("UTF8.txt", "UTF16.txt", Encoding.UTF8);
        }

// --------------------------------------------------------------------------------------------
// Use the Encoder.Convert() method to convert a file of characters to a file of encoded bytes.
// --------------------------------------------------------------------------------------------
        static void EncoderConvert(String inputFileName, String outputFileName, Encoding enc)
        {
// Convert an input file of characters to an output file of encoded bytes.
// StreamWriter could convert the input file for us, but we'll perform the conversion
// ourselves.

            FileStream fs = new FileStream(outputFileName, FileMode.Create);
            BinaryWriter outputFile = new BinaryWriter(fs);

// StreamReader will detect Unicode encoding from the Byte Order Mark that heads the input file.
            StreamReader inputFile = new StreamReader(inputFileName);

// Get an Encoder.
            Encoder encoder = enc.GetEncoder();

// Guarantee the output buffer large enough to convert a few characters.
            int UseBufferSize = 64;
            if (UseBufferSize < enc.GetMaxByteCount(10))
                    UseBufferSize = enc.GetMaxByteCount(10);
            byte[] bytes = new byte[UseBufferSize];

// Intentionally make the input character buffer larger than the output byte buffer so the
// conversion loop executes more than one cycle.

            char[] chars = new char[UseBufferSize * 4];
            int charsRead;
            do
            {
// Read at most the number of characters that will fit in the input buffer. The return
// value is the actual number of characters read, or zero if no characters remain.
                charsRead = inputFile.Read(chars, 0, UseBufferSize * 4);

                bool completed = false;
                int charIndex = 0;
                int charsUsed;
                int bytesUsed;

                while (!completed)
                {
// If this is the last input data, flush the encoder's internal buffer and state.

                    bool flush = (charsRead == 0);
                    encoder.Convert(chars, charIndex, charsRead - charIndex,
                                    bytes, 0, UseBufferSize, flush,
                                    out charsUsed, out bytesUsed, out completed);

// The conversion produced the number of bytes indicated by bytesUsed. Write that number
// of bytes to the output file.
                    outputFile.Write(bytes, 0, bytesUsed);

// Increment charIndex to the next block of characters in the input buffer, if any, to convert.
                    charIndex += charsUsed;
                }
            }
            while(charsRead != 0);

            outputFile.Close();
            fs.Close();
            inputFile.Close();
        }

// --------------------------------------------------------------------------------------------
// Use the Decoder.Convert() method to convert a file of encoded bytes to a file of characters.
// --------------------------------------------------------------------------------------------
        static void DecoderConvert(String inputFileName, String outputFileName, Encoding enc)
        {
// Convert an input file of of encoded bytes to an output file characters.
// StreamWriter could convert the input file for us, but we'll perform the conversion
// ourselves.

            StreamWriter outputFile = new StreamWriter(outputFileName, false, Encoding.Unicode);

// Read the input as a binary file so we can detect the Byte Order Mark.
            FileStream fs = new FileStream(inputFileName, FileMode.Open);
            BinaryReader inputFile = new BinaryReader(fs);

// Get a Decoder.
            Decoder decoder = enc.GetDecoder();

// Guarantee the output buffer large enough to convert a few characters.
            int UseBufferSize = 64;
            if (UseBufferSize < enc.GetMaxCharCount(10))
                    UseBufferSize = enc.GetMaxCharCount(10);
            char[] chars = new char[UseBufferSize];

// Intentionally make the input byte buffer larger than the output character buffer so the
// conversion loop executes more than one cycle.

            byte[] bytes = new byte[UseBufferSize * 4];
            int bytesRead;
            do
            {
// Read at most the number of bytes that will fit in the input buffer. The
// return value is the actual number of bytes read, or zero if no bytes remain.

                bytesRead = inputFile.Read(bytes, 0, UseBufferSize * 4);

                bool completed = false;
                int byteIndex = 0;
                int bytesUsed;
                int charsUsed;

                while (!completed)
                {
// If this is the last input data, flush the decoder's internal buffer and state.

                    bool flush = (bytesRead == 0);
                    decoder.Convert(bytes, byteIndex, bytesRead - byteIndex,
                                    chars, 0, UseBufferSize, flush,
                                    out bytesUsed, out charsUsed, out completed);

// The conversion produced the number of characters indicated by charsUsed. Write that number
// of characters to the output file.

                    outputFile.Write(chars, 0, charsUsed);

// Increment byteIndex to the next block of bytes in the input buffer, if any, to convert.
                    byteIndex += bytesUsed;
                }
            }
            while(bytesRead != 0);

            outputFile.Close();
            fs.Close();
            inputFile.Close();
        }

// --------------------------------------------------------------------------------------------
// Create a large file of UTF-16 encoded Unicode characters.
// --------------------------------------------------------------------------------------------
        static void CreateTestFile(String FileName)
        {
// StreamWriter defaults to UTF-8 encoding so explicitly specify Unicode, that is,
// UTF-16, encoding.
            StreamWriter file = new StreamWriter(FileName, false, Encoding.Unicode);

// Write a line of text 100 times.
            for (int i = 0; i < 100; i++)
            {
                file.WriteLine("This is an example input file used by the convert example.");
            }

// Write Unicode characters from U+0000 to, but not including, the surrogate character range.
            for (char c = (char)0; c < (char)0xD800; c++)
            {
                file.Write(c);
            }
            file.Close();
        }
    }

/*
This code example produces the following results:

(Execute the -dir- console window command and examine the files created.)

Example.txt, which contains 122,594 bytes (61,297 UTF-16 encoded characters).
UTF8.txt, which contains 169,712 UTF-8 encoded bytes.
UTF16.txt, which contains 122,594 bytes (61,297 UTF-16 encoded characters).

(Execute the -comp- console window command and compare the two Unicode files.)

>comp example.txt utf16.txt /L
Comparing example.txt and utf16.txt...
Files compare OK

(The two files are equal.)

*/
' This code example demonstrates the Encoder.Convert() and Decoder.Convert methods. 
' This example uses files for input and output, but any source that can be expressed
' as a stream can be used instead.

Imports System.Text
Imports System.IO

Public Class Sample
    Shared Sub Main(ByVal args() As String) 
        ' Create a large file of UTF-16 encoded Unicode characters. The file is named Example.txt, 
        ' and is used as input to the Encoder.Convert() method. 
        CreateTestFile("Example.txt")
        
        
        ' Using an input file of UTF-16 encoded characters named Example.txt, create an output file 
        ' of UTF-8 encoded bytes named UTF8.txt.
        EncoderConvert("Example.txt", "UTF8.txt", Encoding.UTF8)
        
        ' Using an input file of UTF-8 encoded bytes named UTF8.txt, create an output file 
        ' of UTF-16 encoded characters named UTF16.txt.
        DecoderConvert("UTF8.txt", "UTF16.txt", Encoding.UTF8)
    
    End Sub
    
    ' --------------------------------------------------------------------------------------------
    ' Use the Encoder.Convert() method to convert a file of characters to a file of encoded bytes.
    ' --------------------------------------------------------------------------------------------
    Shared Sub EncoderConvert(ByVal inputFileName As String, ByVal outputFileName As String, ByVal enc As Encoding) 
        ' Convert an input file of characters to an output file of encoded bytes.
        ' StreamWriter could convert the input file for us, but we'll perform the conversion 
        ' ourselves.
        Dim fs As New FileStream(outputFileName, FileMode.Create)
        Dim outputFile As New BinaryWriter(fs)
        
        ' StreamReader will detect Unicode encoding from the Byte Order Mark that heads the input file.
        Dim inputFile As New StreamReader(inputFileName)
        
        ' Get an Encoder.
        Dim encoder As Encoder = enc.GetEncoder()
        
        ' Guarantee the output buffer large enough to convert a few characters.
        Dim UseBufferSize As Integer = 64
        If UseBufferSize < enc.GetMaxByteCount(10) Then
            UseBufferSize = enc.GetMaxByteCount(10)
        End If
        Dim bytes(UseBufferSize) As Byte
        
        ' Intentionally make the input character buffer larger than the output byte buffer so the 
        ' conversion loop executes more than one cycle. 
        Dim chars(UseBufferSize * 4) As Char
        Dim charsRead As Integer
        Do
            ' Read at most the number of characters that will fit in the input buffer. The return 
            ' value is the actual number of characters read, or zero if no characters remain. 
            charsRead = inputFile.Read(chars, 0, UseBufferSize * 4)
            
            Dim completed As Boolean = False
            Dim charIndex As Integer = 0
            Dim charsUsed As Integer
            Dim bytesUsed As Integer
            
            While Not completed
                ' If this is the last input data, flush the encoder's internal buffer and state.
                Dim flush As Boolean = charsRead = 0
                encoder.Convert(chars, charIndex, charsRead - charIndex, bytes, 0, UseBufferSize, flush, charsUsed, bytesUsed, completed)
                
                ' The conversion produced the number of bytes indicated by bytesUsed. Write that number
                ' of bytes to the output file.
                outputFile.Write(bytes, 0, bytesUsed)
                
                ' Increment charIndex to the next block of characters in the input buffer, if any, to convert.
                charIndex += charsUsed
            End While
        Loop While charsRead <> 0
        
        outputFile.Close()
        fs.Close()
        inputFile.Close()
    
    End Sub
    
    ' --------------------------------------------------------------------------------------------
    ' Use the Decoder.Convert() method to convert a file of encoded bytes to a file of characters.
    ' --------------------------------------------------------------------------------------------
    Shared Sub DecoderConvert(ByVal inputFileName As String, ByVal outputFileName As String, ByVal enc As Encoding) 
        ' Convert an input file of of encoded bytes to an output file characters.
        ' StreamWriter could convert the input file for us, but we'll perform the conversion 
        ' ourselves.
        Dim outputFile As New StreamWriter(outputFileName, False, Encoding.Unicode)
        
        ' Read the input as a binary file so we can detect the Byte Order Mark.
        Dim fs As New FileStream(inputFileName, FileMode.Open)
        Dim inputFile As New BinaryReader(fs)
        
        ' Get a Decoder.
        Dim decoder As Decoder = enc.GetDecoder()
        
        ' Guarantee the output buffer large enough to convert a few characters.
        Dim UseBufferSize As Integer = 64
        If UseBufferSize < enc.GetMaxCharCount(10) Then
            UseBufferSize = enc.GetMaxCharCount(10)
        End If
        Dim chars(UseBufferSize) As Char
        
        ' Intentionally make the input byte buffer larger than the output character buffer so the 
        ' conversion loop executes more than one cycle. 
        Dim bytes(UseBufferSize * 4) As Byte
        Dim bytesRead As Integer
        Do
            ' Read at most the number of bytes that will fit in the input buffer. The 
            ' return value is the actual number of bytes read, or zero if no bytes remain. 
            bytesRead = inputFile.Read(bytes, 0, UseBufferSize * 4)
            
            Dim completed As Boolean = False
            Dim byteIndex As Integer = 0
            Dim bytesUsed As Integer
            Dim charsUsed As Integer
            
            While Not completed
                ' If this is the last input data, flush the decoder's internal buffer and state.
                Dim flush As Boolean = bytesRead = 0
                decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, chars, 0, UseBufferSize, flush, bytesUsed, charsUsed, completed)
                
                ' The conversion produced the number of characters indicated by charsUsed. Write that number
                ' of characters to the output file.
                outputFile.Write(chars, 0, charsUsed)
                
                ' Increment byteIndex to the next block of bytes in the input buffer, if any, to convert.
                byteIndex += bytesUsed
            End While
        Loop While bytesRead <> 0
        
        outputFile.Close()
        fs.Close()
        inputFile.Close()
    
    End Sub
    
    ' --------------------------------------------------------------------------------------------
    ' Create a large file of UTF-16 encoded Unicode characters. 
    ' --------------------------------------------------------------------------------------------
    Shared Sub CreateTestFile(ByVal FileName As String) 
        ' StreamWriter defaults to UTF-8 encoding so explicitly specify Unicode, that is, 
        ' UTF-16, encoding.
        Dim file As New StreamWriter(FileName, False, Encoding.Unicode)
        
        ' Write a line of text 100 times.
        Dim i As Integer
        For i = 0 To 99
            file.WriteLine("This is an example input file used by the convert example.")
        Next i
        
        ' Write Unicode characters from U+0000 to, but not including, the surrogate character range.
        Dim c As Integer
        For c = 0 To &HD800
            file.Write(ChrW(c))
        Next c
        file.Close()
    
    End Sub
End Class

'
'This code example produces the following results:
'
'(Execute the -dir- console window command and examine the files created.)
'
'Example.txt, which contains 122,594 bytes (61,297 UTF-16 encoded characters).
'UTF8.txt, which contains 169,712 UTF-8 encoded bytes.
'UTF16.txt, which contains 122,594 bytes (61,297 UTF-16 encoded characters).
'
'(Execute the -comp- console window command and compare the two Unicode files.)
'
'>comp example.txt utf16.txt /L
'Comparing example.txt and utf16.txt...
'Files compare OK
'
'(The two files are equal.)
'

Comentários

Lembre-se de Encoder que o objeto salva o estado entre chamadas para Convert . Quando o aplicativo é feito com um fluxo de dados, ele deve definir o parâmetro como para garantir que as informações flush true de estado são liberados. Com essa configuração, o codificador ignora bytes inválidos no final do bloco de dados e limpa o buffer interno. Todos os dados processados restantes que fazem parte de uma unidade lógica, como o substituto alto de um par substituto, são convertidos de acordo com as configurações de fallback atuais.

O método foi projetado para ser usado em um loop para codificar uma quantidade arbitrária de entrada, como dados lidos Convert de um arquivo ou fluxo. Ele armazena a saída da operação de codificação em um buffer de tamanho fixo. GetBytes lançará uma exceção se o buffer de saída não for grande o suficiente, mas preencherá o máximo de espaço possível e retornará os Convert caracteres lidos e os bytes gravados. Consulte também o Encoding.GetBytes artigo para obter mais comentários.

O completed parâmetro de saída indica se todos os dados no buffer de entrada foram convertidos e armazenados no buffer de saída. Esse parâmetro será definido como se o número de caracteres especificado pelo parâmetro não puder ser convertido sem exceder o número de false bytes especificado pelo parâmetro charCount byteCount . Nessa situação, o aplicativo deve usar o conteúdo do buffer de saída ou fornecer um novo buffer de saída, incrementar o parâmetro pelo número de caracteres especificados pelo parâmetro e, em seguida, chamar o método novamente para processar a entrada chars charsUsed Convert restante.

O completed parâmetro também pode ser definido como , mesmo que os false charsUsed charCount parâmetros e sejam iguais. Essa situação ocorrerá se ainda houver dados no Encoder objeto que não foram armazenados no chars buffer.

Aplica-se a