Note: This post is part of a series and you can find the rest of the parts in the series index.
.NET 4 has seven (!!) new methods for enumeration of directories, files and contents of files. What makes these stand apart from what we have had before, is these return IEnumerable<T> rather than arrays.
Why is it better to get IEnumerable<T> over an array? Rather than getting all the data into one structure first, the array, and returning a massive lump of data. With IEnumerable<T> it returns it one item at a time, as it enumerates that item. If this doesn’t make sense, see the example below.
Example
Old way
So in this example I use the old method:
DirectoryInfo root = new DirectoryInfo(@"c:\"); var collection = from f in root.GetFiles("*", SearchOption.AllDirectories) select f; foreach (var item in collection) { Console.WriteLine(item); }
However due to some permissions it will fail with an exception. Note where the exception is, it is where we are asking for the files and the the console output at this point is empty because it hasn’t finished loading all the data into the array.
New Way
Now we change it to the new method:
DirectoryInfo root = new DirectoryInfo(@"c:\"); var collection = from f in root.EnumerateFiles("*", SearchOption.AllDirectories) select f; foreach (var item in collection) { Console.WriteLine(item); }This time see how the exception occurred during the iteration of the items and note how the output contains some files now, because it has processed those already.
This is a major advantage of the new IEnumerable<T> versions, because now we do not need to wait for all items to be found first and that means it is easier to do high performance code and threading.
What are the new methods?
The seven methods are:
- Directory.EnumerateDirectories
- This returns IEnumerable<string> of the folder names.
- DirectoryInfo.EnumerateDirectories
- This returns IEnumerable<DirectoryInfo>.
- Directory.EnumerateFiles
- This returns IEnumerable<string> of the files fullname.
- DirectoryInfo.EnumerateFiles
- This returns IEnumerable<FileInfo>.
- Directory.EnumerateFileSystemEntries
- This returns IEnumerable<string> of the file system entries.
- DirectoryInfo.EnumerateFileSystemEntries
- This returns IEnumerable<FileSystemInfo>.
- File.ReadLines
- This returns IEnumerable<string> where each string is a line from text file.