Decoder.Convert Метод

Определение

Преобразует закодированную последовательность байтов в строку или массив символов.

Перегрузки

Имя Описание
Convert(ReadOnlySpan<Byte>, Span<Char>, Boolean, Int32, Int32, Boolean)

Преобразует диапазон закодированных байтов в символы в кодировке UTF-16 и сохраняет результат в другом буфере диапазона.

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

Преобразует буфер закодированных байтов в символы в кодировке UTF-16 и сохраняет результат в другом буфере.

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

Преобразует массив закодированных байтов в символы в кодировке UTF-16 и сохраняет результат в массиве символов.

Комментарии

Помните, что Decoder объект сохраняет состояние между вызовами Convert. Когда приложение выполняется с потоком данных, он должен задать flush параметр, чтобы true убедиться, что сведения о состоянии сбрасываются. С помощью этого параметра декодировщик игнорирует недопустимые байты в конце блока данных и очищает внутренний буфер. Все оставшиеся обработанные данные, которые входят в логическую единицу, например высокий суррогат суррогатной пары, преобразуются в соответствии с текущими резервными параметрами.

Метод Convert предназначен для использования в цикле для декодирования произвольного объема входных данных, таких как данные, считыванные из файла или потока. Он сохраняет выходные данные операции декодирования в буфере фиксированного размера. GetChars вызовет исключение, если выходной буфер не достаточно велик, но Convert будет заполнять максимальное пространство и возвращать записанные байты, если выходной массив позволяет по крайней мере два символа. Дополнительные комментарии см. в разделе Encoding.GetChars "Дополнительные комментарии".

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

Исходный код:
Decoder.cs
Исходный код:
Decoder.cs
Исходный код:
Decoder.cs
Исходный код:
Decoder.cs
Исходный код:
Decoder.cs

Преобразует диапазон закодированных байтов в символы в кодировке UTF-16 и сохраняет результат в другом буфере диапазона.

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

Параметры

bytes
ReadOnlySpan<Byte>

Диапазон байтов только для чтения, содержащий последовательность для преобразования.

chars
Span<Char>

Диапазон для хранения преобразованных символов.

flush
Boolean

Значение , указывающее, что дополнительные данные не преобразуются; в противном случае .

bytesUsed
Int32

При возврате этого метода содержит количество байтов, созданных преобразованием. Этот параметр передается неинициализирован.

charsUsed
Int32

При возврате этого метода содержит количество символов, chars используемых в преобразовании. Этот параметр передается неинициализирован.

completed
Boolean

При возврате этого метода содержит true , если были преобразованы все указанные символы; в противном случае false. Этот параметр передается неинициализирован.

Комментарии

Выходной completed параметр указывает, были ли преобразованы все данные в диапазоне входных байтов и сохранены в диапазоне chars. Этот параметр имеет false значение, если число байтов, содержащихся в диапазоне входных байтов, не может быть преобразовано без превышения количества символов в диапазоне chars. В этой ситуации приложение должно использовать содержимое выходного буфера или предоставить новый выходной буфер, увеличить bytes параметр по количеству байтов, указанного bytesUsed параметром, а затем снова вызвать Convert метод для обработки оставшихся входных данных.

Параметр completed также можно задать false, несмотря на то, что bytesUsed длина диапазона байтов и параметра равна. Эта ситуация возникает, если в объекте Decoder все еще есть данные, которые не были сохранены в диапазоне bytes .

Применяется к

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

Исходный код:
Decoder.cs
Исходный код:
Decoder.cs
Исходный код:
Decoder.cs
Исходный код:
Decoder.cs
Исходный код:
Decoder.cs

Внимание

Этот API несовместим с CLS.

Альтернативный вариант, совместимый с CLS
System.Text.Decoder.Convert(Byte[], Int32, Int32, Char[], Int32, Int32, Boolean, Int32, Int32, Boolean)

Преобразует буфер закодированных байтов в символы в кодировке UTF-16 и сохраняет результат в другом буфере.

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

Параметры

bytes
Byte*

Адрес буфера, содержащего последовательности байтов для преобразования.

byteCount
Int32

Количество байтов для bytes преобразования.

chars
Char*

Адрес буфера для хранения преобразованных символов.

charCount
Int32

Максимальное количество символов, chars используемых в преобразовании.

flush
Boolean

Значение , указывающее, что дополнительные данные не преобразуются; в противном случае .

bytesUsed
Int32

При возврате этого метода содержит количество байтов, созданных преобразованием. Этот параметр передается неинициализирован.

charsUsed
Int32

При возврате этого метода содержит количество символов, chars используемых в преобразовании. Этот параметр передается неинициализирован.

completed
Boolean

При возврате этого метода содержит true , если все символы, указанные byteCount преобразовывались; в противном случае false. Этот параметр передается неинициализирован.

Атрибуты

Исключения

chars или bytes есть null (Nothing).

charCount или byteCount меньше нуля.

Выходной буфер слишком мал, чтобы содержать любой из преобразованных входных данных. Выходной буфер должен иметь по крайней мере 2 символа размера, чтобы разместить по крайней мере одну суррогатную пару символов.

Произошла резервная ошибка (дополнительные сведения см. в разделе "Кодировка символов" в .NET)

-и-

Fallback задан как DecoderExceptionFallback.

Комментарии

Выходной completed параметр указывает, были ли преобразованы все данные во входном буфере и сохранены в выходном буфере. Этот параметр имеет false значение, если число байтов, указанное параметром, не может быть преобразовано без превышения числа символов, указанных byteCount параметром charCount . В этой ситуации приложение должно использовать содержимое выходного буфера или предоставить новый выходной буфер, увеличить bytes параметр по количеству байтов, указанного bytesUsed параметром, а затем снова вызвать Convert метод для обработки оставшихся входных данных.

Параметр completed также можно задать false, даже если bytesUsedbyteCount параметры равны. Эта ситуация возникает, если в объекте Decoder все еще есть данные, которые не были сохранены в буфере bytes .

Применяется к

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

Исходный код:
Decoder.cs
Исходный код:
Decoder.cs
Исходный код:
Decoder.cs
Исходный код:
Decoder.cs
Исходный код:
Decoder.cs

Преобразует массив закодированных байтов в символы в кодировке UTF-16 и сохраняет результат в массиве символов.

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

Параметры

bytes
Byte[]

Преобразуемый массив байтов.

byteIndex
Int32

Первый элемент bytes преобразования.

byteCount
Int32

Количество преобразованных bytes элементов.

chars
Char[]

Массив для хранения преобразованных символов.

charIndex
Int32

Первый элемент, chars в котором хранятся данные.

charCount
Int32

Максимальное количество элементов, используемых chars в преобразовании.

flush
Boolean

Значение , указывающее, что дополнительные данные не преобразуются; в противном случае .

bytesUsed
Int32

При возврате этого метода содержит количество байтов, которые использовались в преобразовании. Этот параметр передается неинициализирован.

charsUsed
Int32

При возврате этого метода содержит количество символов, chars созданных преобразованием. Этот параметр передается неинициализирован.

completed
Boolean

При возврате этого метода содержит true , если все символы, указанные byteCount преобразовывались; в противном случае false. Этот параметр передается неинициализирован.

Атрибуты

Исключения

chars или bytes есть null (Nothing).

charIndex, , charCountbyteIndexили byteCount меньше нуля.

–или–

Длина chars - charIndex меньше.charCount

–или–

Длина bytes - byteIndex меньше.byteCount

Выходной буфер слишком мал, чтобы содержать любой из преобразованных входных данных. Выходной буфер должен иметь по крайней мере 2 символа размера, чтобы разместить по крайней мере одну суррогатную пару символов.

Произошла резервная ошибка (дополнительные сведения см. в разделе "Кодировка символов" в .NET)

-и-

Fallback задан как DecoderExceptionFallback.

Примеры

В следующем примере метод используется Convert для преобразования файла символов UTF-16 в UTF-8. Затем он использует Convert метод для преобразования символов UTF-8 обратно в символы 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.)
'

Комментарии

Выходной completed параметр указывает, были ли преобразованы все данные во входном буфере и сохранены в выходном буфере. Этот параметр имеет false значение, если число байтов, указанное параметром, не может быть преобразовано без превышения числа символов, указанных byteCount параметром charCount . В этой ситуации приложение должно использовать содержимое выходного буфера или предоставить новый выходной буфер, увеличить bytes параметр по количеству байтов, указанного bytesUsed параметром, а затем снова вызвать Convert метод для обработки оставшихся входных данных.

Параметр completed также можно задать false, даже если bytesUsedbyteCount параметры равны. Эта ситуация возникает, если в объекте Decoder все еще есть данные, которые не были сохранены в буфере bytes .

Применяется к