0
0
CsharpHow-ToBeginner · 3 min read

How to Use File.ReadAllLines in C# - Simple Guide

Use File.ReadAllLines in C# to read all lines from a text file into a string array at once. This method takes the file path as input and returns an array where each element is a line from the file.
📐

Syntax

The File.ReadAllLines method reads all lines from a specified file and returns them as a string array.

  • string path: The full path to the file you want to read.
  • Returns: string[] where each element is a line from the file.
csharp
string[] lines = File.ReadAllLines(path);
💻

Example

This example shows how to read all lines from a file named example.txt and print each line to the console.

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt";

        // Read all lines from the file
        string[] lines = File.ReadAllLines(filePath);

        // Print each line
        foreach (string line in lines)
        {
            Console.WriteLine(line);
        }
    }
}
Output
Hello, world! Welcome to File.ReadAllLines. This reads all lines at once.
⚠️

Common Pitfalls

Common mistakes when using File.ReadAllLines include:

  • Providing an incorrect or non-existent file path, which causes a FileNotFoundException.
  • Not handling exceptions for file access issues like permissions or locked files.
  • Using ReadAllLines on very large files, which can consume a lot of memory since it reads the entire file at once.

Always ensure the file exists and consider using try-catch blocks to handle errors gracefully.

csharp
try
{
    string[] lines = File.ReadAllLines("missingfile.txt");
}
catch (FileNotFoundException)
{
    Console.WriteLine("File not found. Please check the path.");
}
Output
File not found. Please check the path.
📊

Quick Reference

Parameter/ReturnDescription
string pathFull path to the file to read
string[]Array of lines read from the file
Throws IOExceptionIf file is inaccessible or locked
Throws FileNotFoundExceptionIf file does not exist
Reads entire file at onceMay use high memory for large files

Key Takeaways

File.ReadAllLines reads all lines from a file into a string array in one call.
Always provide the correct file path and handle exceptions to avoid crashes.
Avoid using ReadAllLines for very large files to prevent high memory use.
Use try-catch blocks to manage file access errors gracefully.
Each element in the returned array corresponds to one line from the file.