How to open a plain text file in C#?


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".

Updated on: 22-Jun-2020

227 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements