The File
class in the System.IO
namespace provides the ReadAllLines()
method, which is used to read all lines of a text file and return an array of strings containing all the lines of the file.
It takes the path of the file to read as an input and returns an array of strings.
The below scenarios are possible exceptions of this function:
Finally, we will print this array of strings using the foreach
loop.
The program will terminate after printing the output below:
first line of file
second line of file
third line of file
fourth line of file
fifth line of file
using System;using System.IO;class FileLineReader{public static void Main(){string filePath = @"test.txt";if(!File.Exists(filePath)){Console.WriteLine("File does not exist :{0} ", filePath);return;}string[] textFromFile = File.ReadAllLines(filePath);foreach (string line in textFromFile){Console.WriteLine(line);}}}