marți, 11 septembrie 2012

Fast Facts - BinaryReader

This post is about the BinaryReader class and the ReadBytes method return value.

public virtual byte[] ReadBytes( int count )

This method returns an array of count bytes or the number of bytes left to the end of the underlying stream, whichever is less.
When there are no more bytes to read, calling ReadBytes return an empty array of bytes, not a null value. This is useful to know when verifying the outcome of a read operation.
To prove this, there is a quick C# method that you can load in LINQPad:

public static void Main()
    const int arrayLength = 20;

    // Create random data to write to the stream. 
    byte[] dataArray = new byte[arrayLength];
    new Random().NextBytes(dataArray);

    BinaryWriter binWriter = new BinaryWriter(new MemoryStream());

    // Write the data to the stream.
    Console.WriteLine("Writing the data.");

    // Create the reader using the stream from the writer.
    BinaryReader binReader = 
        new BinaryReader(binWriter.BaseStream);

    // Set Position to the beginning of the stream.
    binReader.BaseStream.Position = 0;

    // Read and verify the data. 
    byte[] verifyArray = null;
    for( int i = 0; i < 6; i++ )
        // ReadBytes returns an empty array when there are no more bytes to read.
        verifyArray = binReader.ReadBytes(sizeof(uint));
        Console.WriteLine( (verifyArray!=null) ? "Length = " + verifyArray.Length : "Array is null" );
        verifyArray = null;

Running this program will display:

Writing the data.
Length = 4
Length = 4
Length = 4
Length = 4
Length = 4
Length = 0

Niciun comentariu:

Trimiteți un comentariu