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.

Sharing is Caring...

Other Related Posts:

  1. Read From File In C++
  2. Write To File in C#
  3. Using the Timer Class
  4. Write To File In C++
  5. Read/Write Registry Keys

{ 4 comments… read them below or add one }

George Lindemann Jr May 28, 2008 at 10:37 am

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

Reply

admin May 29, 2008 at 9:28 pm

Can you post here some piece of that code? I can’t tell you now what’s the problem.

Reply

Visual C# Kicks March 28, 2009 at 4:37 am

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

Reply

Visual C# Kicks September 27, 2009 at 4:37 am

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

Reply

Leave a Comment

Spam protection by WP Captcha-Free

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.