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