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#,
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-
Hello, world!
This is a test.
Writing sample text to a file using C# StreamWriter class.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
C# StreamReader for Reading file
In C#, reading a file using the
StreamReaderclass is simple.Example-
Here is a simple example to read data from text file using StreamReader class in C#,
In the above example-
File.Exists(filePath)to check if the file exists.StreamReaderinstance named reader and pass the file path to its constructor.ReadLine()method of theStreamReaderinstance.Output-
Also, Read: How to write file using StreamWriter in C#?