To read a file line by line in C#, you commonly use the StreamReader class.
Best Class: System.IO.StreamReader
Example:
using System;
using System.IO;
class Program
{
static void Main()
{
using (StreamReader reader = new StreamReader("file.txt"))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
StreamReader.ReadLine() reads one line at a time.
The using statement ensures the file is closed properly after reading.
Alternative: File.ReadLines()
For simpler cases, you can use File.ReadLines(), which is more concise and memory-efficient for large files:
foreach (string line in File.ReadLines("file.txt"))
{
Console.WriteLine(line);
}
Also reads lazily (line by line), unlike File.ReadAllLines() which reads the entire file at once.
Summary
Class/Method
Description
Reads Line-by-Line?
StreamReader
Low-level, full control
Yes
File.ReadLines()
Recommended for simplicity
Yes
File.ReadAllLines()
Loads all lines into memory array
No (not lazy)
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To read a file line by line in C#, you commonly use the
StreamReaderclass.Best Class:
System.IO.StreamReaderExample:
StreamReader.ReadLine()reads one line at a time.usingstatement ensures the file is closed properly after reading.Alternative:
File.ReadLines()For simpler cases, you can use
File.ReadLines(), which is more concise and memory-efficient for large files:Also reads lazily (line by line), unlike
File.ReadAllLines()which reads the entire file at once.Summary
StreamReaderFile.ReadLines()File.ReadAllLines()