Quick Answer

Efficiently process text files.

Understanding the Issue

Use StreamReader within using statements for automatic resource cleanup. File.ReadLines() is lightweight for large files.

The Problem

This code demonstrates the issue:

Csharp Error
// Need to process a large log file

The Solution

Here's the corrected code:

Csharp Fixed
// Option 1: StreamReader
using (var reader = new StreamReader("file.txt"))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        Process(line);
    }
}

// Option 2: File.ReadLines (lazy)
foreach (string line in File.ReadLines("large.log"))
{
    Process(line);
}

Key Takeaways

Always dispose file resources with using blocks.