web analytics

File.ReadLines vs File.ReadAllLines in C#

Options

codeling 1602 - 6666
@2016-01-09 14:00:37

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);
}

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com