How to Read a File using StreamReader in C#?

Category > CSHARP || Published on : Wednesday, March 15, 2023 || Views: 239 || C# file handling StreamReader ReadLine Close method.


Reading a file in C# is a common task in many applications, whether it's for reading configuration files, log files or any other type of file. One way to read a file in C# is by using the StreamReader class. In this article, we'll look at how to use StreamReader to read a file in C#.

Step 1: Create a StreamReader object The first step in reading a file with StreamReader is to create a StreamReader object. This is done by passing the path of the file to the constructor of the StreamReader class. For example, to read a file called "example.txt" located in the "C:\temp" directory, the following code can be used:

using System.IO;

StreamReader reader = new StreamReader(@"C:\temp\example.txt");

Step 2: Read the file Once a StreamReader object has been created, you can read the file using the ReadLine method. This method reads a single line from the file and returns it as a string. You can call this method repeatedly to read each line of the file. For example:

string line;
while ((line = reader.ReadLine()) != null)
{
    Console.WriteLine(line);
}

In this example, we use a while loop to read each line of the file until the end of the file is reached. The ReadLine method returns null when there are no more lines to read.

Step 3: Close the StreamReader After reading the file, it's important to close the StreamReader to release any system resources that it's using. This is done by calling the Close method of the StreamReader object. For example:

reader.Close();

Full Example Code:

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // Create a StreamReader object
        StreamReader reader = new StreamReader(@"C:\temp\example.txt");

        // Read the file
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }

        // Close the StreamReader
        reader.Close();

        Console.ReadLine();
    }
}

In conclusion, the StreamReader class in C# provides a simple and efficient way to read a file. By following the above steps, you can easily read the contents of a file and process them in your application.