Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
file handling
communitycreator

How to read all lines from a file in C#

Siddharth Singh

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.

Syntax

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:

  • The input file path is null or empty, or has whitespace or invalid characters.
  • The input file path or the file name is longer than the system-defined limit.
  • The path is invalid or there is an IO error while opening or reading the file.
  • The caller of the method does not have the right permission.
  • The file is not found or represents a directory.
  • The operation is not supported on the operating system.

Code example

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
main.cs
test.txt
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

c#
file handling
communitycreator
RELATED COURSES

View all Courses

Keep Exploring