.NET 4 Baby Steps: Part VIII - Enumerate Directories and Files

_ Baby looking at camera 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 enumerating directories, files, and file contents. What makes these stand apart from what we had before is that they return IEnumerable<T> rather than arrays.

Why is it better to get IEnumerable<T> over an array? Rather than loading all the data into one structure first—the array—and returning a massive lump of data, IEnumerable<T> returns items one at a time as they are enumerated. 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 permission issues, it will fail with an exception. Note that the exception occurs where we ask for the files, and the console output at this point is empty because it hasn’t finished loading all the data into the array.

The unexpected exception

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 occurs during the iteration of the items and note how the output contains some files already, as they have been processed.

The unexpected exception

This is a major advantage of the new IEnumerable<T> versions, as we no longer need to wait for all items to be found first. This means it’s easier to write high-performance code and use threading.

What Are the New Methods?

The seven methods are: