How to Read a text file line by line in C#
By Tan Lee Published on Mar 05, 2025 138
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.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization
Categories
Popular Posts
Horizon MUI Admin Dashboard Template
Nov 18, 2024
Elegent Material UI React Admin Dashboard Template
Nov 19, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024
Material Lite Admin Template
Nov 14, 2024