Skip to main content
.NET Framework Class Library
BinaryReaderRead 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
Assemblies:   System.IO (in System.IO.dll)
  mscorlib (in mscorlib.dll)
Syntax
Public Overridable Function Read ( _
	buffer As [%$TOPIC/ms143295_en-us_VS_110_1_0_0_0_0%](), _
	index As [%$TOPIC/ms143295_en-us_VS_110_1_0_0_0_1%], _
	count As [%$TOPIC/ms143295_en-us_VS_110_1_0_0_0_2%] _
) As [%$TOPIC/ms143295_en-us_VS_110_1_0_0_0_3%]
public virtual [%$TOPIC/ms143295_en-us_VS_110_1_0_1_0_0%] Read(
	[%$TOPIC/ms143295_en-us_VS_110_1_0_1_0_1%][] buffer,
	[%$TOPIC/ms143295_en-us_VS_110_1_0_1_0_2%] index,
	[%$TOPIC/ms143295_en-us_VS_110_1_0_1_0_3%] count
)
public:
virtual [%$TOPIC/ms143295_en-us_VS_110_1_0_2_0_0%] Read(
	array<[%$TOPIC/ms143295_en-us_VS_110_1_0_2_0_1%]>^ buffer, 
	[%$TOPIC/ms143295_en-us_VS_110_1_0_2_0_2%] index, 
	[%$TOPIC/ms143295_en-us_VS_110_1_0_2_0_3%] count
)
abstract Read : 
        buffer:[%$TOPIC/ms143295_en-us_VS_110_1_0_3_0_0%][] * 
        index:[%$TOPIC/ms143295_en-us_VS_110_1_0_3_0_1%] * 
        count:[%$TOPIC/ms143295_en-us_VS_110_1_0_3_0_2%] -> [%$TOPIC/ms143295_en-us_VS_110_1_0_3_0_3%]  
override Read : 
        buffer:[%$TOPIC/ms143295_en-us_VS_110_1_0_3_0_4%][] * 
        index:[%$TOPIC/ms143295_en-us_VS_110_1_0_3_0_5%] * 
        count:[%$TOPIC/ms143295_en-us_VS_110_1_0_3_0_6%] -> [%$TOPIC/ms143295_en-us_VS_110_1_0_3_0_7%]
public function Read(
	buffer : [%$TOPIC/ms143295_en-us_VS_110_1_0_4_0_0%][], 
	index : [%$TOPIC/ms143295_en-us_VS_110_1_0_4_0_1%], 
	count : [%$TOPIC/ms143295_en-us_VS_110_1_0_4_0_2%]
) : [%$TOPIC/ms143295_en-us_VS_110_1_0_4_0_3%]

Parameters

buffer
Type: SystemByte

The buffer to read data into.

index
Type: SystemInt32

The starting point in the buffer at which to begin reading into the buffer.

count
Type: SystemInt32

The number of bytes to read.

Return Value

Type: SystemInt32
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.
Exceptions
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 .

ArgumentOutOfRangeException

index or count is negative.

ObjectDisposedException

The stream is closed.

IOException

An I/O error occurs.

Remarks

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.

Examples

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

Imports System.IO

Module Module1

    Sub Main()
        Const upperBound As Integer = 1000
        Dim dataArray(upperBound) As Byte 
        Dim verifyArray(upperBound) As Byte 

        Dim randomGenerator As New Random
        randomGenerator.NextBytes(dataArray)

        Using binWriter As New BinaryWriter(New MemoryStream())
            Console.WriteLine("Writing the data.")
            binWriter.Write(dataArray, 0, dataArray.Length)

            Using binReader As New BinaryReader(binWriter.BaseStream)
                binReader.BaseStream.Position = 0

                If binReader.Read(verifyArray, 0, dataArray.Length) <> dataArray.Length Then
                    Console.WriteLine("Error writing the data.")
                    Return 
                End If 
            End Using 
        End Using 

        For i As Integer = 0 To upperBound
            If verifyArray(i) <> dataArray(i) Then
                Console.WriteLine("Error writing the data.")
                Return 
            End If 
        Next i

        Console.WriteLine("The data was written and verified.")
    End Sub 

End Module
using System;
using System.IO;

namespace BinaryRW
{
    class Program
    {
        static void Main(string[] args)
        {
            const int arrayLength = 1000;
            byte[] dataArray = new byte[arrayLength];
            byte[] verifyArray = new byte[arrayLength];

            new Random().NextBytes(dataArray);

            using (BinaryWriter binWriter = new BinaryWriter(new MemoryStream()))
            {
                Console.WriteLine("Writing the data.");
                binWriter.Write(dataArray, 0, arrayLength);

                using (BinaryReader binReader = new BinaryReader(binWriter.BaseStream))
                {
                    binReader.BaseStream.Position = 0;

                    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

Module Module1
    Private ReadOnly CHUNK_SIZE As Integer = 1024
    Public Sub Main(args() As String)
        If ((args.Length = 0) OrElse Not File.Exists(args(0))) Then
            Console.WriteLine("Please provide an existing file name.")
        Else 
            Using fs As FileStream = New FileStream(args(0), FileMode.Open, FileAccess.Read)
                Using br As New BinaryReader(fs, New ASCIIEncoding())
                    Dim chunk(CHUNK_SIZE) As Byte
                    chunk = br.ReadBytes(CHUNK_SIZE)

                    While chunk.Length > 0
                        DumpBytes(chunk, chunk.Length)
                        chunk = br.ReadBytes(CHUNK_SIZE)
                    End While 
                End Using 
            End Using 
        End If 
    End Sub 

    Public 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 Module
using System;
using System.IO;
using System.Text;

public class DumpFileSample
{
    private static readonly int CHUNK_SIZE = 1024;
    public static void Main(String[] args)
    {
        if ((args.Length == 0) || !File.Exists(args[0]))
        {
            Console.WriteLine("Please provide an existing file name.");
        }
        else
        {
            using (FileStream fs = new FileStream(args[0], FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader br = new BinaryReader(fs, new ASCIIEncoding()))
                {
                    byte[] chunk;

                    chunk = br.ReadBytes(CHUNK_SIZE);
                    while(chunk.Length > 0)
                    {
                        DumpBytes(chunk, chunk.Length);
                        chunk = br.ReadBytes(CHUNK_SIZE);
                    }
                }
            }
        }
    }

    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);
        }
    }
}
Version Information

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Portable Class Library

Supported in: Portable Class Library