What is the difference between File.ReadLines() and File.ReadAllLines()? [duplicate]

is there any performance difference related to these methods?

YES there is a difference

File.ReadAllLines() method reads the whole file at a time and returns the string[] array, so it takes time while working with large size of files and not recommended as user has to wait untill the whole array is returned.

File.ReadLines() returns an IEnumerable<string> and it does not read the whole file at one go, so it is really a better option when working with large size files.

From MSDN:

The ReadLines and ReadAllLines methods differ as follows:

When you use ReadLines, you can start enumerating the collection of strings before
the whole collection is returned; when you use ReadAllLines, you must
wait for the whole array of strings be returned before you can access
the array. Therefore, when you are working with very large files,
ReadLines can be more efficient.

Example 1: File.ReadAllLines()

string[] lines = File.ReadAllLines("C:\\mytxt.txt");

Example 2: File.ReadLines()

foreach (var line in File.ReadLines("C:\\mytxt.txt"))
{

   //Do something     

}

Leave a Comment