0
0
CsharpHow-ToBeginner · 3 min read

How to Read File Line by Line in C# - Simple Guide

In C#, you can read a file line by line using File.ReadLines() or StreamReader.ReadLine(). These methods let you process each line one at a time without loading the entire file into memory.
📐

Syntax

There are two common ways to read a file line by line in C#:

  • File.ReadLines(path): Returns an enumerable collection of lines from the file.
  • StreamReader.ReadLine(): Reads one line at a time from a file stream.

Use File.ReadLines for simple iteration and StreamReader when you need more control over reading.

csharp
foreach (string line in File.ReadLines("file.txt"))
{
    // process line
}

using (StreamReader reader = new StreamReader("file.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // process line
    }
}
💻

Example

This example shows how to read a file named example.txt line by line and print each line to the console using File.ReadLines.

csharp
using System;
using System.IO;

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

        foreach (string line in File.ReadLines(filePath))
        {
            Console.WriteLine(line);
        }
    }
}
Output
Hello, world! This is line 2. This is line 3.
⚠️

Common Pitfalls

Common mistakes when reading files line by line include:

  • Using File.ReadAllLines() for very large files, which loads the entire file into memory and can cause performance issues.
  • Not properly disposing StreamReader, which can lock the file. Always use using to ensure disposal.
  • Assuming lines are never null. Always check for null when using StreamReader.ReadLine() to avoid errors.
csharp
/* Wrong way: Not disposing StreamReader */
StreamReader reader = new StreamReader("file.txt");
string line = reader.ReadLine();
// File remains locked until reader is disposed

/* Right way: Using 'using' to dispose */
using (StreamReader reader = new StreamReader("file.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
📊

Quick Reference

Here is a quick summary of methods to read files line by line in C#:

MethodDescriptionUse Case
File.ReadLines(path)Returns IEnumerable<string> for each lineSimple, memory-efficient iteration
StreamReader.ReadLine()Reads one line at a time from streamMore control, manual reading
File.ReadAllLines(path)Reads all lines into string arraySmall files only, loads entire file

Key Takeaways

Use File.ReadLines for simple and memory-efficient line-by-line reading.
Use StreamReader with a using block for manual control and safe resource handling.
Avoid File.ReadAllLines for large files to prevent high memory use.
Always check for null when reading lines with StreamReader.ReadLine.
Dispose StreamReader properly to avoid file locks.