How to open a plain text file in C#?

CsharpProgrammingServer Side Programming

To open a plain text file, use the StreamReader class. The following opens a file for reading −

StreamReader sr = new StreamReader("d:/new.txt")

Now, display the content of the file −

while ((line = sr.ReadLine()) != null) {
   Console.WriteLine(line);
}

Here is the code −

Example

 Live Demo

using System;
using System.IO;

namespace FileApplication {
   class Program {
      static void Main(string[] args) {
         try {

            using (StreamReader sr = new StreamReader("d:/new.txt")) {
               string line;

               // Read and display lines from the file until
               // the end of the file is reached.
               while ((line = sr.ReadLine()) != null) {
                  Console.WriteLine(line);
               }
            }
         } catch (Exception e) {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
         }
         Console.ReadKey();
      }
   }
}

Output

The file could not be read:
Could not find a part of the path "/home/cg/root/4281363/d:/new.txt".
raja
Published on 31-Aug-2018 15:05:09
Advertisements