Reader Level:
Articles

How to read a text file in C#

By Mahesh Chand on July 30, 2010
This code sample shows how to read text files in C#.
  • 1
  • 0
  • 47961
Download Files:
 

We can use StreamReader to read text files. The following code snippet reads a file and writes on the console line by line.

string fileName = @"C:\Mahesh\McTextFile.txt";

 

// Read a text file using StreamReader

using (System.IO.StreamReader sr = new System.IO.StreamReader(fileName))

{

    String line;

    while ((line = sr.ReadLine()) != null)

    {

        Console.WriteLine(line);

    }

}

 

Console.WriteLine("StreamReader Done");

Console.WriteLine("========================");




Another approach is to use File.OpenText method and read a text file.

 

// Read using File.OpenText

if (System.IO.File.Exists(fileName))

{

    using (System.IO.StreamReader sr = System.IO.File.OpenText(fileName))

    {

        String input;

        while ((input = sr.ReadLine()) != null)

        {

            Console.WriteLine(input);

        }

        Console.WriteLine("Finished.");

    }

}

else

{

    Console.WriteLine("File not found");

}

           

Console.WriteLine("File.Opentext Done - Neel wrote it");

 

Console.ReadKey();


Mahesh Chand

Mahesh Chand is founder of C# Corner. C# Corner founded in 1999 is a FREE member contributions based open platform for developers to solve problems, learn new technology and hang out.  Mahesh has been awar... Read more

COMMENT USING

Trending up