c-sharp
  1. c-sharp-streamreader

C# StreamReader

In C#, the StreamReader class is used to read text files. StreamReader makes it easy to read the contents of a file as a stream of characters, line by line or as a whole. In this tutorial, we'll discuss how to use StreamReader in C#.

Syntax

The syntax for creating a StreamReader in C# is as follows:

StreamReader reader = new StreamReader(filePath);

Here, "reader" is the name of the StreamReader object, and "filePath" is the path to the file that you want to read.

Example

Let's say we have a text file called "example.txt" in our project folder. Here's how we can use StreamReader to read the contents of the file:

using System.IO;

class Program {
    static void Main(string[] args) {
        string filePath = "example.txt";

        // Create a StreamReader object
        StreamReader reader = new StreamReader(filePath);

        // Read the contents of the file
        string contents = reader.ReadToEnd();

        // Close the StreamReader object
        reader.Close();

        // Print the contents of the file to the console
        Console.WriteLine(contents);
    }
}

Output

When we run the example code above, the output will be the contents of the "example.txt" file.

Explanation

In the example above, we created a StreamReader object to read the contents of a text file called "example.txt". We used the ReadToEnd method to read all the contents of the file and store it in a string variable called "contents". We then closed the StreamReader object and printed the contents of the file to the console.

Use

StreamReader is useful when you need to read the contents of a text file in your C# application. You can use it to read text files as a stream of characters, line by line, or as a whole.

Important Points

  • Always call the Close method on the StreamReader object to release the file handle and free up resources.
  • You can use the static File class to open a file and create a StreamReader object.
  • StreamReader can also read from other streams, such as network streams or memory streams.

Summary

In this tutorial, we discussed how to use StreamReader in C# to read the contents of a text file. We covered the syntax, example, output, explanation, use, and important points of StreamReader in C#. With this knowledge, you can now use StreamReader in your C# application to read the contents of text files.

Published on: