Playing with FindFirstFile and FindNextFile

Enumerating files in .NET is easy. Everybody knows the GetFiles method and you may be tempted to write code like this :

But if you look closer you will notice that this method returns an array of strings. This could be problematic if the directory you search contains lots of files. The method will block until it performs the search and once it finishes it will load all the results into memory. It would be much better if it just returned an IEnumerable. That’s exactly what the EnumerateFiles method does in .NET 4.0. Unfortunately in .NET 3.5 there’s nothing for the job.

In this post I will show how to implement this functionality using the FindFirstFile and FindNextFile functions.

We start by defining the native function prototypes:

You may notice the SafeFindHandle class used in the method signatures. This is just a simple class deriving from SafeHandle that will make sure that unmanaged handle is correctly closed:

As the documentation states the handle created by FindFirstFile needs to be closed with FindClose function. And finally the implementation of the EnumerateFiles method:

The method could be used like this:

Leave a comment

Your email address will not be published. Required fields are marked *