Free System Design Interview Course
Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.
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.
public static string[] ReadAllLines (string filePath);
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:
In the following code example, a text file (test.txt) already exists in the current working directory. We will first check if this file exists, and then read all the lines of the file to a string array.
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);}}}
RELATED TAGS
CONTRIBUTOR