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

I have a request regarding File.ReadLines () and File.ReadAllLines (). What is the difference between them. I have a text file where it contains data on a line. File.ReadAllLines() return array and using File.ReadLines().ToArray(); I can also get the same result. Is there a performance difference associated with these methods?

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

or

 string[] lines = File.ReadAllLines("C:\\mytxt.txt"); 
+20
source share
3 answers

is there any performance difference associated with these methods?

Yes there is a difference

File.ReadAllLines() method reads the entire file at a time and returns an array [], so it takes time to work with large file sizes and is not recommended, as the user must wait until the entire array is returned.

File.ReadLines() returns an IEnumerable<string> , and it does not read the entire file at a time, so this is really the best option when working with large files.

From MSDN :

The ReadLines and ReadAllLines methods are distinguished as follows:

When you use ReadLines, you can start listing a collection of strings before the entire collection is returned; when you use ReadAllLines, you must wait until the entire array of strings is returned before you can access the array. Therefore, when you work with very large files, ReadLines may 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 } 
+38
source

File.ReadLines Returns the IEnumerable<string> method. But File.ReadAllLines returns string[] If you are reading a Large file, you better use the File.ReadLines method. because it reads the line after the line from the file, and does not read the entire file in string[] , which takes up a lot of memory. MSDN

+2
source

ReadAllLine

Opens a text file, reads all lines of the file and closes the file.

If you have small files or you need to process the full file immediately, use it because it reads the file completely, which means that the entire file is in your memory. In the case of large files, this can slow performance.

ReadLine

Using the File.ReadLines method, we read only one line.

Read the files one at a time if you need to process the file not necessarily right away.

Below is detailed information and a comparison demonstration.

0
source

All Articles