
File.ReadLines reads lines as you process them. You want to read all the lines in from a file in a foreach loop, but only as needed. With the File.ReadLines method, you can read in another line before each iteration of your foreach loop.
This C# example program demonstrates the File.ReadLines method from System.IO.
To begin, this program calls the File.ReadLines method in the foreach loop iteration block. The File.ReadLines method is only called once; then, the IEnumerable<string> is used to pull in more data. The program successfully prints the data found in the file.txt file in the C directory.
Program that uses File.ReadLines [C#]
using System;
using System.IO;
class Program
{
static void Main()
{
// Read in lines from file.
foreach (string line in File.ReadLines("c:\\file.txt"))
{
Console.WriteLine("-- {0}", line);
}
}
}
Output
-- Line1
-- Line2
-- Line3
-- Another line.
-- Last line.
The File.ReadLines and File.ReadAllLines methods are different in their implementation. The File.ReadLines method uses an enumerator internally to read each line only as needed. On the other hand, the File.ReadAllLines method reads the entire file into memory and then returns an array of those lines.
If the file is very large, the File.ReadLines method is useful because it will not need to keep all the data in memory at once. Also, if your program exits the loop early, the File.ReadLines is better because no further IO will be needed. The File.ReadAllLines method is best if you need the entire array.

The File.ReadLines method is similar to using the StreamReader type and the ReadLine method in a loop. Essentially, it is a different interface to that functionality. With File.ReadLines, you can simplify your code somewhat and use a simple foreach loop to read in an entire file line-by-line.
File Handling