Export (0) Print
Expand All

BinaryReader.Read Method (Byte[], Int32, Int32)

Reads the specified number of bytes from the stream, starting from a specified point in the byte array.

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

public virtual int Read(
	byte[] buffer,
	int index,
	int count
)

Parameters

buffer
Type: System.Byte[]
The buffer to read data into.
index
Type: System.Int32
The starting point in the buffer at which to begin reading into the buffer.
count
Type: System.Int32
The number of bytes to read.

Return Value

Type: System.Int32
The number of bytes read into buffer. This might be less than the number of bytes requested if that many bytes are not available, or it might be zero if the end of the stream is reached.

ExceptionCondition
ArgumentException

The buffer length minus index is less than count.

-or-

The number of decoded characters to read is greater than count. This can happen if a Unicode decoder returns fallback characters or a surrogate pair.

ArgumentNullException

buffer is null.

ArgumentOutOfRangeException

index or count is negative.

ObjectDisposedException

The stream is closed.

IOException

An I/O error occurs.

BinaryReader does not restore the file position after an unsuccessful read operation.

For a list of common I/O tasks, see Common I/O Tasks.

The following example shows how to write binary data using memory as a backing store. It then displays a message to the console that indicates whether the data was written correctly.


using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        const int arrayLength = 1000;

        // 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.");
        binWriter.Write(dataArray, 0, arrayLength);

        // 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 = new byte[arrayLength];
        if(binReader.Read(verifyArray, 0, arrayLength) != arrayLength)
        {
            Console.WriteLine("Error writing the data.");
            return;
        }
        for(int i = 0; i < arrayLength; i++)
        {
            if(verifyArray[i] != dataArray[i])
            {
                Console.WriteLine("Error writing the data.");
                return;
            }
        }
        Console.WriteLine("The data was written and verified.");
    }
}


This example reads the contents of a file and displays each byte's numeric value in 16 column format. The end of the file that is being read is detected when the Read method returns zero bytes.


Imports System
Imports System.IO
Imports System.Text

Public Class DumpFileSample
    Private Shared ReadOnly CHUNK_SIZE As Integer = 1024
    Public Shared Sub Main(args() As String)
        Try
            Dim fs As FileStream
            If args.Length > 0 Then
                fs = New FileStream(args(0), FileMode.Open, FileAccess.Read)
            Else
                Throw New ArgumentException()
            End If
            ' use one byte per character encoding for reading dump data
            Dim br As New BinaryReader(fs, New ASCIIEncoding())
            Dim chunk() As Byte

            ' read file chunks until end of file
            Do
                chunk = br.ReadBytes(CHUNK_SIZE)
                ' chunk.Length will be 0 if end of file is reached.
                If chunk.Length > 0
                    DumpBytes(chunk, chunk.Length)
                End If
            Loop While chunk.Length > 0
            fs.Close()
        Catch
            Console.WriteLine("Cannot find or read file to dump.")
        End Try
    End Sub

    Public Shared Sub DumpBytes(bdata() As Byte, len As Integer)
        Dim i As Integer
        Dim j As Integer = 0
        Dim dchar As Char
        ' 3 * 16 chars for hex display, 16 chars for text and 8 chars
        ' for the 'gutter' int the middle.
        Dim dumptext As New StringBuilder("        ", 16 * 4 + 8)
        For i = 0 to len -1
            dumptext.Insert(j * 3, String.Format("{0:X2} ", CType(bdata(i), Integer)))
            dchar = Convert.ToChar(bdata(i))
            ' replace 'non-printable' chars with a '.'.
            If Char.IsWhiteSpace(dchar) Or Char.IsControl(dchar) Then
                dchar = "."
            End If
            dumptext.Append(dchar)
            j += 1
            If j = 16 Then
                Console.WriteLine(dumptext)
                dumptext.Length = 0
                dumptext.Append("        ")
                j = 0
            End If
        Next i
        ' display the remaining line
        If j > 0 Then
            ' add blank hex spots to align the 'gutter'.
            For i = j To 15
                dumptext.Insert(j * 3, "   ")
            Next i
            Console.WriteLine(dumptext)
        End If
    End Sub
End Class



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

public class DumpFileSample
{
    private static readonly int CHUNK_SIZE = 1024;
    public static void Main(String[] args)
    {
        try
        {
            FileStream fs;
            if (args.Length > 0)
            {
                fs = new FileStream(args[0], FileMode.Open, FileAccess.Read);
            }
            else
            {
                throw new ArgumentException();
            }
            // use one byte per character encoding for reading dump data
            BinaryReader br = new BinaryReader(fs, new ASCIIEncoding());
            byte[] chunk;

            // read file chunks until end of file
            do
            {
                // chunk.Length will be 0 if end of file is reached.
                chunk = br.ReadBytes(CHUNK_SIZE);
                if (chunk.Length > 0)
                {
                    DumpBytes(chunk, chunk.Length);
                }
            }
            while (chunk.Length > 0);
            fs.Close();
        }
        catch
        {
            Console.WriteLine("Cannot find or read file to dump.");
        }
    }

    public static void DumpBytes(byte[] bdata, int len)
    {
        int i;
        int j = 0;
        char dchar;
        // 3 * 16 chars for hex display, 16 chars for text and 8 chars
        // for the 'gutter' int the middle.
        StringBuilder dumptext = new StringBuilder("        ", 16 * 4 + 8);
        for (i = 0; i < len; i++)
        {
            dumptext.Insert(j * 3, String.Format("{0:X2} ", (int)bdata[i]));
            dchar = (char)bdata[i];
            //' replace 'non-printable' chars with a '.'.
            if ( Char.IsWhiteSpace(dchar) || Char.IsControl(dchar))
            {
                dchar = '.';
            }
            dumptext.Append(dchar);
            j++;
            if (j == 16)
            {
                Console.WriteLine(dumptext);
                dumptext.Length = 0;
                dumptext.Append("        ");
                j = 0;
            }
        }
        // display the remaining line
        if (j > 0)
        {
            for (i = j; i < 16; i++)
            {
                dumptext.Insert(j * 3, "   ");
            }
            Console.WriteLine(dumptext);
        }
    }
}



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

public class DumpFileSample
{
    private static readonly int CHUNK_SIZE = 1024;
    public static void Main(String[] args)
    {
        try
        {
            FileStream fs;
            if (args.Length > 0)
            {
                fs = new FileStream(args[0], FileMode.Open, FileAccess.Read);
            }
            else
            {
                throw new ArgumentException();
            }
            // use one byte per character encoding for reading dump data
            BinaryReader br = new BinaryReader(fs, new ASCIIEncoding());
            byte[] chunk = new byte[CHUNK_SIZE];
            int chunksize;

            // read file chunks until end of file
            do
            {
                // chunksize will be 0 if end of file is reached.
                chunksize = br.Read(chunk, 0, CHUNK_SIZE);
                if (chunksize > 0)
                {
                    DumpBytes(chunk, chunksize);
                }
            }
            while (chunksize > 0);
            fs.Close();
        }
        catch
        {
            Console.WriteLine("Cannot find or read file to dump.");
        }
    }

    public static void DumpBytes(byte[] bdata, int len)
    {
        int i;
        int j = 0;
        char dchar;
        // 3 * 16 chars for hex display, 16 chars for text and 8 chars
        // for the 'gutter' int the middle.
        StringBuilder dumptext = new StringBuilder("        ", 16 * 4 + 8);
        for (i = 0; i < len; i++)
        {
            dumptext.Insert(j * 3, String.Format("{0:X2} ", (int)bdata[i]));
            dchar = (char)bdata[i];
            //' replace 'non-printable' chars with a '.'.
            if ( Char.IsWhiteSpace(dchar) || Char.IsControl(dchar))
            {
                dchar = '.';
            }
            dumptext.Append(dchar);
            j++;
            if (j == 16)
            {
                Console.WriteLine(dumptext);
                dumptext.Length = 0;
                dumptext.Append("        ");
                j = 0;
            }
        }
        // display the remaining line
        if (j > 0)
        {
            for (i = j; i < 16; i++)
            {
                dumptext.Insert(j * 3, "   ");
            }
            Console.WriteLine(dumptext);
        }
    }
}



using namespace System;
using namespace System::IO;
using namespace System::Text;

public ref class DumpFileSample
{
private:
    static const int CHUNK_SIZE = 1024;

public:
    static void Main(array<String^>^ args)
    {
        try
        {
            FileStream^ fs;
            if (args->Length > 1)
            {
                fs = gcnew FileStream(args[1], FileMode::Open, FileAccess::Read);
            }
            else
            {
                throw gcnew ArgumentException();
            }
            // use one byte per character encoding for reading dump data
            BinaryReader^ br = gcnew BinaryReader(fs, gcnew ASCIIEncoding());
            array<Byte>^ chunk = gcnew array<Byte>(CHUNK_SIZE);
            int chunksize;

            // read file chunks until end of file
            do
            {
                chunksize = br->Read(chunk, 0, CHUNK_SIZE);
                // chunksize will be 0 if end of file is reached.
                if (chunksize > 0)
                {
                    DumpBytes(chunk, chunksize);
                }
            }
            while (chunksize > 0);
            fs->Close();
        }
        catch (...)
        {
            Console::WriteLine("Cannot find or read file to dump.");
        }
    }

    static void DumpBytes(array<Byte>^ bdata, int len)
    {
        int i;
        int j = 0;
        Char dchar;
        // 3 * 16 chars for hex display, 16 chars for text and 8 chars
        // for the 'gutter' int the middle.
        StringBuilder^ dumptext = gcnew StringBuilder("        ", 16 * 4 + 8);
        for (i = 0; i < len; i++)
        {
            dumptext->Insert(j * 3, String::Format("{0:X2} ", (int)bdata[i]));
            dchar = (Char)bdata[i];
            // replace 'non-printable' chars with a '.'.
            if ( Char::IsWhiteSpace(dchar) || Char::IsControl(dchar))
            {
                dchar = '.';
            }
            dumptext->Append(dchar);
            j++;
            if (j == 16)
            {
                Console::WriteLine(dumptext);
                dumptext->Length = 0;
                dumptext->Append("        ");
                j = 0;
            }
        }
        // display the remaining line
        if (j > 0)
        {
            for (i = j; i < 16; i++)
            {
                dumptext->Insert(j * 3, "   ");
            }
            Console::WriteLine(dumptext);
        }
    }
};

int main()
{
    DumpFileSample::Main(Environment::GetCommandLineArgs());
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

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

Community Additions

ADD
Show:
© 2014 Microsoft