New methods are added to the System.IO.File class in .NET framework 4.0 for reading and writing text files.
In earlier version we have used File.ReadAllLines method which returns a string array of all lines in the file.
String lines = File.ReadAllLines(â€œfile.txtâ€);
The issue is it must read all lines and allocate an array to return. For small files its ok but large files it is problematic because it block until all the lines are loaded into the memory.
The new method ReadLines in .NET framework 4 returns IEnumerable<string> instead of string. The new method is much more efficient because it does not load all of the lines into memory at once;
IEnumerable<string> lines = File.ReadLines(â€œLargefile.txtâ€);
Foreach(var line in lines)
The iteration actually driving the reading of the file.
The other two new methods are File.WriteAllLines that takes an IEnumerable<string>
Parameter and File.ApendAllLines that takes an IEnumerable<string> for appending lines to a file.
In earlier version we have used GetFiles() method on directoryinfo object to get all files in the directory.
DirectoryInfo directory = new DirectoryInfo(@â€œLargeDirectoryâ€);
FileInfo files = directory.GetFiles();
The issue is it must retrieve the complete list of files in the directory and then allocate an array to return. Here we have to wait all files to be retrieved.
The second issue is whenever we call the properties on retrieved file it takes an additional call to the file which hinders the performance.
In .NET 4, new method has added to Directory and DirectoryInfo that returns IEnumerable<T> instead of arrays to address the above issues.
DirectoryInfo directory = new DirectoryInfo(@â€œLargeDirectoryâ€); IEnumerable<FileInfo> files = directory.EnumerateFiles();
Unlike GetFiles, EnumerateFiles does not have to block until all of the files are retrieved. Now the DirectoryInfo object containing the file system during enumeration which include data about each file such as length and creation time.
|Share this post :|
yet another nice post; I will definitely make use of these methods when dealing with text intensive windows form applications