In .NET Framework, the File.ReadLines and File.ReadAllLines methods in C# File Class can be used to read all the lines in from a file, but they are different in their implementation:
- The File.ReadLines method uses an enumerator internally to read each line only as needed,
- 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.
using File.ReadLines
foreach (string line in File.ReadLines("c:\\file.txt"))
{
Console.WriteLine(line);
}
using File.ReadAllLines
foreach (string line in File.ReadAllLines("c:\\file.txt"))
{
Console.WriteLine(line);
}