[C#] Reading a Text File Line by Line (File.ReadLines)

There are several ways to read the contents of a text file. The File.ReadLines method is unique because it uses “lazy execution,” which means it reads data bit by bit as needed. This makes it extremely memory-efficient when handling massive files, such as log files, or when you only need to check the first few lines.

目次

Implementation Sample: Reading the First 10 Lines

In the following code, the program does not load the entire file into memory. Instead, it retrieves lines one by one and stops reading immediately after reaching the 10th line.

Sample Code

using System;
using System.IO;
using System.Linq; // Required for methods like Take

public class Program
{
    public static void Main()
    {
        // Path of the file to read
        string filePath = "example.txt";

        // 1. Preparation: Create a dummy file for testing (100 lines)
        if (!File.Exists(filePath))
        {
            // Create a file containing 100 lines of data
            File.WriteAllLines(filePath, Enumerable.Range(1, 100).Select(i => $"Line Number {i}"));
        }

        Console.WriteLine($"--- Displaying the first 10 lines of {filePath} ---");

        // 2. Read using File.ReadLines
        // At this point, the entire file has not been loaded into memory yet
        var lines = File.ReadLines(filePath);

        // By using Take(10), file access stops once 10 lines are read
        foreach (var line in lines.Take(10))
        {
            Console.WriteLine(line);
        }
    }
}

Execution Result

--- Displaying the first 10 lines of example.txt ---
Line Number 1
Line Number 2
...
Line Number 10

Explanation and Choosing the Right Loading Method

C# provides several methods to read files. It is important to choose the right one based on your needs.

MethodReturn ValueFeatures and Usage
File.ReadLinesIEnumerable<string>Recommended. Reads one line at a time (lazy execution). Ideal for processing data with loops (foreach) or LINQ while keeping memory usage low.
File.ReadAllTextstringRetrieves the entire file content as a single, concatenated string. Use this for parsing JSON or searching the entire text with regular expressions.
File.ReadAllLinesstring[]Reads all lines into a string array. This is convenient for small files where you need random access (e.g., jumping directly to lines[5]).

Why is ReadLines the Best Choice?

If you use ReadAllLines to read a log file that is several gigabytes in size, the program will attempt to load all that data into memory as an array. This often leads to an OutOfMemoryException.

In contrast, ReadLines only keeps the “current line” being processed in the loop in memory. This allows you to handle massive files safely and efficiently.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次