This documentation is archived and is not being maintained.

Decoder.Convert Method (Byte[], Int32, Int32, Char[], Int32, Int32, Boolean, Int32, Int32, Boolean)

Note: This method is new in the .NET Framework version 2.0.

Converts an array of encoded bytes to Unicode characters and stores the result in a byte array.

Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)

[ComVisibleAttribute(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
)
/** @attribute ComVisibleAttribute(false) */ 
public void Convert (
	byte[] bytes, 
	int byteIndex, 
	int byteCount, 
	char[] chars, 
	int charIndex, 
	int charCount, 
	boolean flush, 
	/** @attribute OutAttribute() */ /** @ref */ int bytesUsed, 
	/** @attribute OutAttribute() */ /** @ref */ int charsUsed, 
	/** @attribute OutAttribute() */ /** @ref */ boolean completed
)
JScript does not support passing value-type arguments by reference.

Parameters

bytes

A byte array to convert.

byteIndex

The first element of bytes to convert.

byteCount

The number of elements of bytes to convert.

chars

An array to store the converted characters.

charIndex

The first element of chars in which data is stored.

charCount

The maximum number of elements of chars to use in the conversion.

flush

true to indicate that no further data is to be converted; otherwise, false.

bytesUsed

When this method returns, contains the number of bytes that were used in the conversion. This parameter is passed uninitialized.

charsUsed

When this method returns, contains the number of characters from chars that were produced by the conversion. This parameter is passed uninitialized.

completed

When this method returns, contains true if all the characters specified by byteCount were converted; otherwise, false. This parameter is passed uninitialized.

Exception typeCondition

ArgumentNullException

chars or bytes is a null reference (Nothing in Visual Basic).

ArgumentOutOfRangeException

charIndex, charCount, byteIndex, or byteCount is less than zero.

-or-

The length of chars - charIndex is less than charCount.

-or-

The length of bytes - byteIndex is less than byteCount.

ArgumentException

The output buffer is too small to contain any of the converted input. The output buffer should be greater than or equal to the size indicated by the GetCharCount method.

The Convert method is designed to be used in a loop to encode an arbitrary amount of input, such as data read from a file or stream, and store the output of the encoding operation in a fixed-sized buffer.

The current Decoder object maintains internal data and state information between iterations of the processing loop. Set the flush parameter to true to indicate that no further data is expected, and that the Decoder object can discard any unprocessed data and return to a default state. Any remaining processed data that is part of a logical unit, such as the high surrogate of a surrogate pair, is converted according to the current fallback settings.

The completed output parameter indicates whether all the data in the input array was converted and stored in the output array. The completed output parameter is false if the number of bytes specified by the byteCount parameter cannot be converted without exceeding the number of characters specified by the charCount parameter. In that situation, use the contents of the output buffer or provide a new output buffer, increment the byteIndex parameter by the number of bytes specified by the bytesUsed parameter, then call the Convert method again to process the remaining input.

The completed parameter can also be false, even though the bytesUsed and byteCount parameters are equal, if there is still data in the Decoder object that has not been stored in the chars array.

The following code example uses the Encoder.Convert(Char[],Int32,Int32,Byte[],Int32,Int32,Boolean,Int32,Int32,Boolean) method to convert a file of UTF-16 characters to UTF-8, then uses the Decoder.Convert(Byte[],Int32,Int32,Char[],Int32,Int32,Boolean,Int32,Int32,Boolean) method to convert the UTF-8 characters back to UTF-16 characters.

// 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.)

*/

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

.NET Compact Framework

Supported in: 2.0
Show: