BinaryReader.Read Method

Definition

Reads bytes from the underlying stream and advances the current position of the stream.

Overloads

Read()

Reads characters from the underlying stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.

Read(Span<Byte>)

Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

Read(Span<Char>)

Reads, from the current stream, the same number of characters as the length of the provided buffer, writes them in the provided buffer, and advances the current position in accordance with the Encoding used and the specific character being read from the stream.

Read(Byte[], Int32, Int32)

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

Read(Char[], Int32, Int32)

Reads the specified number of characters from the stream, starting from a specified point in the character array.

Read()

Source:
BinaryReader.cs
Source:
BinaryReader.cs
Source:
BinaryReader.cs

Reads characters from the underlying stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream.

C#
public virtual int Read();

Returns

The next character from the input stream, or -1 if no characters are currently available.

Exceptions

An I/O error occurred.

The stream is closed.

Examples

The following example shows how to read and write data using memory as a backing store. This example displays a list of invalid file path characters to the console. Although the code tries to display a list of all invalid file path characters, not all of the characters are within the displayable set of characters. Because the list of invalid characters can vary based on the system, output for this code may also vary.

C#
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i = 0;
        char[] invalidPathChars = Path.InvalidPathChars;
        MemoryStream memStream = new MemoryStream();
        BinaryWriter binWriter = new BinaryWriter(memStream);

        // Write to memory.
        binWriter.Write("Invalid file path characters are: ");
        for(i = 0; i < invalidPathChars.Length; i++)
        {
            binWriter.Write(invalidPathChars[i]);
        }

        // Create the reader using the same MemoryStream
        // as used with the writer.
        BinaryReader binReader = new BinaryReader(memStream);

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

        // Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString());
        char[] memoryData =
            new char[memStream.Length - memStream.Position];
        for(i = 0; i < memoryData.Length; i++)
        {
            memoryData[i] = Convert.ToChar(binReader.Read());
        }
        Console.WriteLine(memoryData);
    }
}

Remarks

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

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

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Read(Span<Byte>)

Source:
BinaryReader.cs
Source:
BinaryReader.cs
Source:
BinaryReader.cs

Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.

C#
public virtual int Read(Span<byte> buffer);

Parameters

buffer
Span<Byte>

A region of memory. When this method returns, the contents of this region are replaced by the bytes read from the current source.

Returns

The total number of bytes read into the buffer. This can be less than the number of bytes allocated in the buffer if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

Exceptions

The stream is closed.

An I/O error occurred.

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Standard 2.1

Read(Span<Char>)

Source:
BinaryReader.cs
Source:
BinaryReader.cs
Source:
BinaryReader.cs

Reads, from the current stream, the same number of characters as the length of the provided buffer, writes them in the provided buffer, and advances the current position in accordance with the Encoding used and the specific character being read from the stream.

C#
public virtual int Read(Span<char> buffer);

Parameters

buffer
Span<Char>

A span of characters. When this method returns, the contents of this region are replaced by the characters read from the current source.

Returns

The total number of characters read into the buffer. This might be less than the number of characters requested if that many characters are not currently available, or it might be zero if the end of the stream is reached.

Exceptions

The stream is closed.

An I/O error occurred.

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Standard 2.1

Read(Byte[], Int32, Int32)

Source:
BinaryReader.cs
Source:
BinaryReader.cs
Source:
BinaryReader.cs

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

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

Parameters

buffer
Byte[]

The buffer to read data into.

index
Int32

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

count
Int32

The number of bytes to read.

Returns

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

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.

buffer is null.

index or count is negative.

The stream is closed.

An I/O error occurred.

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.

C#
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.

C#
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);
        }
    }
}

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.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Read(Char[], Int32, Int32)

Source:
BinaryReader.cs
Source:
BinaryReader.cs
Source:
BinaryReader.cs

Reads the specified number of characters from the stream, starting from a specified point in the character array.

C#
public virtual int Read(char[] buffer, int index, int count);

Parameters

buffer
Char[]

The buffer to read data into.

index
Int32

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

count
Int32

The number of characters to read.

Returns

The total number of characters read into the buffer. This might be less than the number of characters requested if that many characters are not currently available, or it might be zero if the end of the stream is reached.

Exceptions

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.

buffer is null.

index or count is negative.

The stream is closed.

An I/O error occurred.

Examples

The following example shows how to read and write data using memory as a backing store. This example displays a list of invalid file path characters to the console. Although the code tries to display a list of all invalid file path characters, not all of the characters are within the displayable set of characters. Because the list of invalid characters can vary based on the system, output for this code may also vary.

C#
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        char[] invalidPathChars = Path.InvalidPathChars;
        MemoryStream memStream = new MemoryStream();
        BinaryWriter binWriter = new BinaryWriter(memStream);

        // Write to memory.
        binWriter.Write("Invalid file path characters are: ");
        binWriter.Write(
            Path.InvalidPathChars, 0, Path.InvalidPathChars.Length);

        // Create the reader using the same MemoryStream
        // as used with the writer.
        BinaryReader binReader = new BinaryReader(memStream);

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

        // Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString());
        int arraySize = (int)(memStream.Length - memStream.Position);
        char[] memoryData = new char[arraySize];
        binReader.Read(memoryData, 0, arraySize);
        Console.WriteLine(memoryData);
    }
}

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.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0