C# StreamReader Code Examples

Introduction

C# StreamReader is used to read characters to a stream in a specified encoding. StreamReader.Read method reads the next character or next set of characters from the input stream. StreamReader is inherited from TextReader which provides methods to read a character, block, line, or all content.

StreamReader is defined in the System.IO namespace. StreamReader provides the following methods.

  1. Peak: Returns if there is a character or not.
  2. Read: Reads the next character or next set of characters from the input stream.
  3. ReadAsync: Reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index.
  4. ReadBlock: Reads a specified maximum number of characters from the current stream and writes the data to a buffer, beginning at the specified index.
  5. ReadBlockAsync: Reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index.
  6. ReadLine: Reads a line of characters from the current stream and returns the data as a string.
  7. ReadLineAsync: Reads a line of characters asynchronously from the current stream and returns the data as a string.
  8. ReadToEnd: Reads all characters from the current position to the end of the stream.
  9. ReadToEndAsync: Reads all characters from the current position to the end of the stream asynchronously and returns them as one string.

Creating a StreamReader from a Filename

StreamReader constructor takes a full file name or a FileStream object with Encoding and buffer size as optional parameters.

The following code snippet creates a StreamReader from a filename with default encoding and buffer size. 

// File name
string fileName = @"C:\Temp\CSharpAuthors.txt";
StreamReader reader = new StreamReader(fileName);

The following code example creates a StreamReader that reads file content one line at a time and displays it to the console. If there is an exception, the exception is displayed on the console.

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

class Program
{
    static void Main(string[] args)
    {
        // File name
        string fileName = @"C:\Temp\CSharpAuthors.txt";

        try
        {
            // Create a StreamReader
            using (StreamReader reader = new StreamReader(fileName))
            {
                string line;
                // Read line by line
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception exp)
        {
            Console.WriteLine(exp.Message);
        }

        Console.ReadKey();
    }
}

In the above example, the file name is the complete path, including a file on a Universal Naming Convention (UNC) share. The default encoding is UTF8Encoding, and the buffer size to 1024 bytes.

Creating a StreamReader using FileInfo.OpenText

StreamReader can be created using the FileInfo.OpenText() method. The following code snippet creates a StreamReader using the FileInfo.OpenText() method. 

FileInfo fi = new FileInfo(fileName);
StreamReader sr = fi.OpenText();
string s = "";

while ((s = sr.ReadLine()) != null)
{
    Console.WriteLine(s);
}

FileInfo class is useful with file operations. Learn more about FileInfo class here: FileInfo in C#

Creating a StreamReader using a FileStream

StreamReader constructor takes a FileStream object with Encoding and buffer size as optional parameters. The following code snippet creates a StreamReader from a FileStream with default encoding and buffer size.

// Create a StreamReader from a FileStream
using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open)))
{
    string line;
    // Read line by line
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

The following code snippet creates a StreamReader from a FileStream with Encoding. Encoding supported are ASCII, Unicode, UTF32, UTF7, and UTF8. Encoding is defined in the System.Text namespace.

using (StreamReader reader = new StreamReader(  
new FileStream(fileName, FileMode.Open), Encoding.UTF8))  

The following code snippet creates a StreamReader from a FileStream with encoding and buffer size. 

using (StreamReader reader = new StreamReader(  
new FileStream(fileName, FileMode.Open), Encoding.UTF8, true, 1024))  

To learn more about Encoding in C#, visit Encoding/Decoding in C#. 

StreamReader.Peak() method

Stream.Reader.Peek() method checks if there are more characters left to read in a file. The method returns an integer. If the value is less than 0, there are no more characters left to read. The following code snippet uses the Peak() method to check if there are more characters left to read in a file.

// Create a StreamReader
using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open)))
{
    while (reader.Peek() >= 0)
    {
        // Read here
    }
}

StreamReader.ReadBlock() method

StreamReader.Read() method reads a specified maximum number of characters from the current stream and writes the data to a buffer, beginning at the specified index. The position of the underlying stream is advanced by the number of characters that were read into the buffer. The method blocks until either count characters are read or the end of the stream has been reached. This is a blocking version of Read.

StreamReader.ReadBlockAsync() method reads a specified maximum number of characters from the current stream asynchronously and writes the data to a buffer, beginning at the specified index. 

StreamReader.Read() method

StreamReader.Read() method reads the next char or next set of chars from the input stream. StreamReader.ReadAsync() method reads the next char or next set of chars from the input stream asynchronously.

The following code snippet reads a stream using the Read() method. 

// Create a StreamReader
using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open)))
{
    while (reader.Peek() >= 0)
    {
        Console.WriteLine((char)reader.Read());
    }
}

StreamReader.ReadLine() method

StreamReader.ReadLine() method reads a line of characters from the current stream and returns the data as a string.

StreamReader.ReadLineAsync() method reads a line of characters from the current stream asynchronously and returns the data as a string.

The following code snippet reads a file using the ReadLine() method. 

// Create a StreamReader from a FileStream
using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open)))
{
    string line;
    // Read line by line
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

StreamReader.ReadToEnd() method

StreamReader.ReadToEnd() method reads all characters from the current position to the end of the stream.

StreamReader.ReadToEndAsync() method reads all characters from the current position to the end of the stream.

The following code snippet reads the entire file using the ReadToEnd() method. 

using (StreamReader reader = new StreamReader(fileName))
{
    Console.WriteLine(reader.ReadToEnd());
}

StreamReader Code Example

Here is the complete code example of the use of StreamReader and its methods. The code also reads the content of the file and displays it on the console. 

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

class Program
{
    static void Main(string[] args)
    {
        // File name
        string fileName = @"C:\Temp\CSharpAuthors.txt";

        try
        {
            using (StreamReader reader = new StreamReader(fileName))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
        }
        catch (Exception exp)
        {
            Console.WriteLine(exp.Message);
        }

        Console.ReadKey();
    }
}

The output of the above code looks like the following:

C# StreamReader 

Summary

In this article and code sample, we saw how to use a StreamReader class to read a text file.

Next > Working with StreamWriter in C# 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.