How to Read a text file line by line in C#
By Tan Lee Published on Mar 05, 2025 213
There are a couple of ways to read a text file line by line:
- File.ReadLines(): Reads small chunks of the file into memory (buffering) and gives you one line at a time.
- File.ReadAllLines(): Reads the entire file into a string array (one string per line).
Using File.ReadLines()
to read a file line by line
This method reads the file incrementally, one line at a time, which makes it memory-efficient.
using System.IO; foreach (var line in File.ReadLines(@"C:\temp\fruits.txt")) { Console.WriteLine(line); }
Output:
apple banana cherry
Using File.ReadAllLines()
to read the entire file into an array
In this case, the entire content of the file is loaded into an array, where each line is an element.
using System.IO; string[] lines = File.ReadAllLines(@"C:\temp\fruits.txt"); foreach (var line in lines) { Console.WriteLine(line); }
Output:
apple banana cherry
Skip the first line using File.ReadLines()
To skip the first line while reading the file, use the LINQ method Skip(1)
.
using System.IO; using System.Linq; foreach (var line in File.ReadLines(@"C:\temp\fruits.txt").Skip(1)) { Console.WriteLine(line); }
Output:
banana cherry
Read just the first line using File.ReadLines()
If you only want the first line of the file, use Take(1)
from LINQ.
using System.IO; using System.Linq; foreach (var line in File.ReadLines(@"C:\temp\fruits.txt").Take(1)) { Console.WriteLine(line); }
Output:
apple
Read a file line by line asynchronously with File.ReadLinesAsync()
For asynchronous reading, you can use File.ReadLinesAsync()
. This was introduced in .NET 7 and returns an IAsyncEnumerable
.
using System.IO; await foreach (var line in File.ReadLinesAsync(@"C:\temp\fruits.txt")) { Console.WriteLine(line); }
apple banana cherry
These methods provide various ways to read files efficiently, depending on your needs.
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
K-WD Tailwind CSS Admin Dashboard Template
Nov 17, 2024
Responsive Animated Login Form
Nov 11, 2024
Responsive Admin Dashboard Template
Nov 11, 2024