Reader Level:
Articles

How to read a text file in C#

By Mahesh Chand on Jul 30, 2010
This code sample shows how to read text files in C#.
  • 1
  • 0
  • 51646
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

C# Corner founder, 10-times Microsoft MVP, technical author, and software architect. Mahesh authored his first book, A Programmer’s Guide to ADO.NET in C# with APress at the age of 25. C# Corner is a memb... Read more

COMMENT USING