In this post we explained how to write text to a file in C#. Today we will explain reading text from a file using the StreamReader class.
So create a file "text.txt" in the same directory where is the executable of the project. We will create a C# Console Application.
First, we must include this namespace, to use the StreamReader class
using System.IO;
Then write this code in the place where you want your program to read the file
StreamReader sr = new StreamReader("text.txt"); string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); }
With this code we read the text written in the file "text.txt" line by line, and print it on the console.
Simple as that.








{ 4 comments… read them below or add one }
I’m trying to use the Std-Out from a process I launch, to read back data
from the process, until either the data I expcet is passed, or a time limit
hgas expired. My problem is that the StreamReader class blocks until the
process writes something
Can you post here some piece of that code? I can’t tell you now what’s the problem.
I too would like to know if there’s a way to keep StreamReader from blocking access to the file. Not sure it’s possible
I too would like to know if there's a way to keep StreamReader from blocking access to the file. Not sure it's possible