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



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
Updated on: 2020-04-03T10:36:03+05:30

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements