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) {

Here is the code −


 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) {
         } catch (Exception e) {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");


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 12:44:26