---
title: "How to read file using StreamReader in C#?"  
description: "How to read file using StreamReader in C#?"  
author: "Sandra Emily"  
published: 2024-06-13  
updated: 2024-06-13  
canonical: https://www.mindstick.com/forum/160739/how-to-read-file-using-streamreader-in-c-sharp  
category: "c#"  
tags: ["c#", "file", "streaming"]  
reading_time: 2 minutes  

---

# How to read file using StreamReader in C#?

How to read [files](https://www.mindstick.com/articles/23302/the-importance-and-advantage-of-keeping-your-important-files-on-the-cloud) using [StreamReader](https://www.mindstick.com/forum/161576/explain-the-difference-between-streamreader-and-file-readalllines) in C#?

## Replies

### Reply by Ashutosh Patel

### C# StreamReader for Reading file

In C#, reading a file using the `StreamReader` class is simple.

## Example-

Here is a simple example to read data from text file using StreamReader class in C#,

```cs
using System;
using System.IO;
class Program
{
   static void Main()
   {
       // Specify the file path
       string filePath = "sample.txt";
       // Check if the file exists in the location
       if (File.Exists(filePath))
       {
           // Creating a StreamReader instance to read from the file
           using (StreamReader reader = new StreamReader(filePath))
           {
               // Read the file line by line
               string line;
               while ((line = reader.ReadLine()) != null)
               {
                   // Print each line to the console
                   Console.WriteLine(line);
               }
           }
       }
       else
       {
           Console.WriteLine("File not found: " + filePath);
       }
       Console.ReadLine();
   }
}
```

## In the above example-

- Specifies the file path of the file we want to read (**sample.txt**).
- We use `File.Exists(filePath)` to check if the file exists.
- If the file exists, we create a `StreamReader` instance named **reader** and pass the file **path** to its constructor.
- We use a **while loop** to read a file line using the `ReadLine()` method of the `StreamReader`instance.
- In the loop, we **print** each line to the **console**.
- The transaction ensures that the **StreamReader** is properly disposed of after use, which locks the file and frees any associated objects.

## Output-

```plaintext
Hello, world!
This is a test.
Writing sample text to a file using C# StreamWriter class.
```

**Also, Read:** [How to write file using StreamWriter in C#?](https://www.mindstick.com/forum/160741/how-to-write-file-using-streamwriter-in-c-sharp)


---

Original Source: https://www.mindstick.com/forum/160739/how-to-read-file-using-streamreader-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
