How to read a text file in C#

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();


Up Next
    Ebook Download
    View all
    Learn
    View all