.NET Framework System.IO Namespace provides File class which contains static methods for various file operations like creation, deletion, opening, copying and moving a file.
Prior to .NET version 4.0 File class provided File.ReadAllLines method that opened a text file, read all lines and then closed the file.
But .NET 4.0 has done some improvement for reading files with much more flexibility with File.ReadLines method.
|
Difference between File.ReadAllLines & File.ReadLines
——————————————————————— File.ReadAllLines opens a file, reads all the lines and returns a string array(string []) of all the lines present in the file. So before it returns the array it must read all the lines and allocate them in an array which can cause performance issue in case of very large files.
e.g. :-
string[] lineContents = File.ReadAllLines(@”D:\FileName.txt”);
foreach (string line in lineContents) { Console.WriteLine(“Line={1}”, line); } In this case before the foreach loop executes all the lines of FileName.txt should be read and loaded into lineContents array which is not acceptable for huge files.
Where as File.ReadLines returns IEnumerable<string> instead of string[]. So Instead of loading all the lines in to memory at once, it reads the lines one at a time.
e.g. :-
IEnumerable<string> lineContents = File.ReadLines(@”D:\FileName.txt”);
foreach (string line in lineContents) { Console.WriteLine(“Line={1}”, line); } Here File.ReadLines just initiate an IEnumerable type and the iteration of foreach loops reads line from the file. Hence you dont have to wait now for all the lines to be read before processing. So if you are working with large files File.Readlines can be more efficient.
Since File.ReadLines method returns an IEnumerable object you can perform LINQ to Objects queries on a file. You can also break out of the loop if necessary without reading all the lines
|