In C#, File.ReadLines() returns the lines of a text file as an IEnumerable<string>. Lines are read lazily: the next line is read from the disk only when your loop asks for it.
That makes it a good choice for big files and for jobs that stop early, such as finding the first match. It combines nicely with LINQ methods like Take, Where, and First.
This is a static method of System.IO.File. Call it as File.ReadLines(...); there is no new File(). For an object that remembers one file, see FileInfo.
Syntax
Loop over the result with foreach, or chain LINQ methods. Add using System.Linq; for LINQ.
C#
string path = Path.Combine(Path.GetTempPath(), "codetofun-readlines.txt");
File.WriteAllLines(path, new[] { "a", "b", "c" });
foreach (string line in File.ReadLines(path)) {
Console.WriteLine(line);
}
Call
What it does
File.ReadLines(path)
Returns a lazy sequence of lines, decoded as UTF-8.
File.ReadLines(path, encoding)
Same, with the encoding you pass.
File.ReadLines(path).Take(5)
Reads only the first five lines and then stops.
ReadLines has no Length, because the file is not fully read yet. Call Count() if you need the number, which reads the whole file once.
Library declarations
C#
public static IEnumerable<string> ReadLines(string path);
public static IEnumerable<string> ReadLines(string path, Encoding encoding);
Parameters
Parameter
Description
path
The text file to read. It must exist.
encoding
Optional. The Encoding used to decode the file. Defaults to UTF-8.
Return Value
Return Value
Description
IEnumerable<string>
A lazy sequence with one string per line. The file stays open until you finish or dispose the loop.
C# Examples
Example 1 — Print Each Line with foreach
Walk through a small file one line at a time.
C#
using System;
using System.IO;
class Program {
static void Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-readlines");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "fruits.txt");
File.WriteAllLines(path, new[] { "apple", "banana", "cherry" });
int total = 0;
foreach (string line in File.ReadLines(path)) {
total += line.Length;
Console.WriteLine(line.ToUpper());
}
Console.WriteLine(total);
Directory.Delete(root, true);
}
}
Output
APPLE
BANANA
CHERRY
17
How It Works
Lines arrive one by one. The foreach loop asks for a line, the file reader supplies it, and the body runs. No array of all lines is built.
Work on each line. The loop prints the upper-case version and adds the length to a running total.
The total.apple has 5 letters, banana has 6, and cherry has 6, so the sum is 17.
Example 2 — Read Only the First Two Lines
Use LINQ Take to stop reading as soon as you have enough.
C#
using System;
using System.IO;
using System.Linq;
class Program {
static void Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-readlines-take");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "five.txt");
File.WriteAllLines(path, Enumerable.Range(1, 5).Select(n => "line " + n));
foreach (string line in File.ReadLines(path).Take(2)) {
Console.WriteLine(line);
}
Directory.Delete(root, true);
}
}
Output
line 1
line 2
How It Works
Five lines on disk.Enumerable.Range(1, 5).Select(...) builds line 1 to line 5, and WriteAllLines accepts that sequence directly.
Take is lazy too.Take(2) asks ReadLines for two lines and then stops asking. The other three lines are never read.
Why it matters. For a file with millions of lines, the same code returns in a moment, while ReadAllLines would load every line first.
Example 3 — Find Error Lines in a Log
Filter with Where, count the matches, and take the first one.
C#
using System;
using System.IO;
using System.Linq;
class Program {
static void Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-readlines-log");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "app.log");
File.WriteAllLines(path, new[] { "INFO start", "ERROR disk", "INFO save", "ERROR net" });
var errors = File.ReadLines(path).Where(line => line.StartsWith("ERROR"));
Console.WriteLine(errors.Count());
Console.WriteLine(errors.First());
Directory.Delete(root, true);
}
}
Output
2
ERROR disk
How It Works
A four line log. Two lines start with ERROR and two start with INFO.
Nothing runs yet.Where only describes the filter. The file is read when Count() asks for the answer, which is 2.
A second pass.First() reads the file again from the top and stops at the first match, ERROR disk. The file must stay unchanged between the two passes.
Frequently Asked Questions
ReadAllLines reads the whole file into a string array first. ReadLines returns an IEnumerable that reads one line at a time, so it can start sooner and use less memory.
Use it for large files, for loops that may stop early, and with LINQ filters such as Where or Take. For small files where you need Length or an index, ReadAllLines is simpler.
The file is still open for reading while the loop runs. Collect the lines you want in a list, finish the loop, and then write.
Yes. Each new loop over the same sequence opens and reads the file again. Call ToList() once if you need to use the lines several times.
Use File.ReadLines(path).Count(). It still reads the whole file, but only one line is in memory at a time.