Back to results for “I/O Streams”
C# › File I/O & Streams

What is the difference between File.ReadAllLines() and File.ReadLines() in terms of memory usage?

Beginner

Answer

File.ReadAllLines() reads the ENTIRE file and returns a fully-materialized string[] array all at once; File.ReadLines() returns a LAZY IEnumerable<string> that reads and yields one line at a time as you iterate, using far less memory for very large files since it never holds the whole file in memory simultaneously.
// Loads the entire file into memory at once
string[] allLines = File.ReadAllLines("huge.txt");

// Reads and processes one line at a time, low memory footprint
foreach (string line in File.ReadLines("huge.txt")) {
  ProcessLine(line);
}
Real-world example Processing a multi-gigabyte log file line by line without loading the entire file into memory.

Common follow-ups: Which method would you choose if you needed to know the total line count before processing?