StreamReader Class in C#

StreamReader class is useful for reading character based data. By default it uses Unicode encoding, it can also work with other character sets, System.Text.Encoding object can be passed to the constructor to make it work with specific character set.

StreamReader derives from an abstract type TextReader. TextReader provides basic functions to Read and Peek into a character stream. StreamReader implements IDisposable interface and also provides Async methods to read data asynchronously.

Some of the methods supported by StreamReader class are list below. For a complete list of methods, please refer to Microsft.NET documentation.

Method Name



Reads the next character from the input stream and advances the position by one.

Read(Char[], Int32, Int32)

Reads the specified number of characters from the input stream and stores them in the buffer. Characters are stored in the buffer starting from the specified index.


Reads the maximum number of characters from the input stream and stored then in the buffer, starting at the specified index.


Reads a line of characters and returns a string.


Reads the characters from the current position to the end of the stream


StreamReader Code Sample

Below code snippet shows how to use StreamReader class. Try to use Using statement when dealing with StreamReader objects, so that the object is disposed immediately.

    // Using statement is used to dispose the object immediately.
    using(StreamReader reader = new StreamReader("input.txt"))

        // Reads a character and moves to the next position.
        int character = reader.Read();
        char [] buffer = new char[100];

        // Reads 10 characters and stores in buffer starting at index 1.
        // Position is adjusted accordingly.
        int result = reader.Read(buffer, 1, 10);

        // Returns the next available character but does not advance the position.
        int peekResult = reader.Peek();

        // Reads next available line and position is adjusted according.
        string line = reader.ReadLine();

        // Reads from current position to the end of the stream.
        string allLinesFromCurrentPosition = reader.ReadToEnd();