How to Read a File Line by Line in C#?
Reading a file line by line is useful when handling large files without loading everything into memory at once.
✅ Best Practice: Use File.ReadLines() which is more memory efficient.
Example
foreach (string line in File.ReadLines("file.txt"))
{
Console.WriteLine(line);
}
Why use ReadLines()?
Reads one line at a time, reducing overall memory usage.
Ideal for large files (e.g., logs, CSVs).
Alternative: Use StreamReader (More Control)
For scenarios where you need custom processing while reading the contents of the file:
using (StreamReader reader = new StreamReader("file.txt"))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Why use StreamReader?
Lets you handle exceptions, encoding, and buffering.
Supports custom processing (e.g., search for a keyword while reading).
When to Use ReadAllLines()?
If you need all lines at once, use:
string[] lines = File.ReadAllLines("file.txt");
Caution: Loads the entire file into memory—avoid for large files!