Read From File Using StreamReader Class

by Shabbir on May 26, 2008

in C#

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.

Share:
  • Digg
  • Facebook
  • StumbleUpon
  • Technorati
  • Twitter

Other Related Posts

Want More Tips on How to Make Money Online?
Enter your Name and Email below to subscribe and start 1 month free course now.

Name:
Email:
You would require to confirm your email address before we send you any updates. We respect your privacy as much as you do.
Powered by Aweber
  • 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
  • admin
    Can you post here some piece of that code? I can't tell you now what's the problem.
  • 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
blog comments powered by Disqus

Previous post:

Next post:

    About the Author

  • author photo

    My Name is Shabbir Bhimani and I am developer by profession in the field of applications, web and database. Currently doing full time online marketing and like to share my experiences on how you can make money online @ CodeItWell.com. Read more ...


    See how you can get in touch with me.