BinaryReader.ReadChars(Int32) Method

Definition

Reads the specified number of characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream.

C#
public virtual char[] ReadChars (int count);

Parameters

count
Int32

The number of characters to read.

Returns

Char[]

A character array containing data read from the underlying stream. This might be less than the number of characters requested if the end of the stream is reached.

Exceptions

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.

The stream is closed.

An I/O error occurred.

count is negative.

Examples

The following code example shows how to read and write data using memory as a backing store.

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);

        // 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());
        Console.WriteLine(binReader.ReadChars(
            (int)(memStream.Length - memStream.Position)));
    }
}

Remarks

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

When reading from network streams, in some rare cases, the ReadChars method might read an extra character from the stream if the BinaryReader was constructed with Unicode encoding. If this occurs, you can use the ReadBytes method to read a fixed-length byte array, and then pass that array to the ReadChars method.

Applies to

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

See also