Using ReadToEnd method
using System.IO;
using System;
// ReadLine method reads only one line at a time,whereas ReadToEnd method Reads all lines from file at a time
class ReadFile
{
static void Main()
{
string fileloc = "D://MyFile.txt"; // File location
// creates file
FileStream fs = new FileStream(fileloc, FileMode.Create);
fs.Close();
Console.WriteLine("File created successfully");
// writes to file
StreamWriter sw = new StreamWriter(fileloc);
sw.WriteLine("first line");
sw.WriteLine("second line");
sw.WriteLine("third line");
sw.Flush();
sw.Close();
Console.WriteLine("Written to file successfully");
// Lets read the file now
Console.WriteLine("Content of file :");
StreamReader sr = new StreamReader(fileloc);
string text = sr.ReadToEnd(); // Entire content is read and stored in string variable
Console.WriteLine(text);
sr.Close();
Console.ReadLine();
}
}
Output:
File created successfully
Written to file successfully
Content of file :
first line
second line
third line