C# Program to read contents of a file into a string at once

CsharpProgrammingServer Side Programming

Use ReadToEnd() method to read the contents of a file in a string.

Set it under StreamReader and read the file −

using (StreamReader sr = new StreamReader("new.txt")){
   string res = sr.ReadToEnd();
   Console.WriteLine(res);
}

The following is the complete code −

Example

 Live Demo

using System.IO;
using System;

public class Demo {
   public static void Main() {
      using (StreamWriter sw = new StreamWriter("new.txt")) {
         sw.WriteLine("One");
         sw.WriteLine("Two");
      }
      using (StreamReader sr = new StreamReader("new.txt")) {
         string res = sr.ReadToEnd();
         Console.WriteLine(res);
      }
   }
}

It creates the file “new.text” and adds text to it. After that, using StreamReader class and ReadToEnd() method, it reads the contents of the file into a string −

Output

The following is the output.

One
Two
raja
Published on 04-Sep-2018 11:39:25
Advertisements