Playing with FindFirstFile and FindNextFile 1

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 *

One thought on “Playing with FindFirstFile and FindNextFile

  • T.J. Crowder

    Great stuff!

    It would be really useful if you listed the “using” statements for each of the above. Otherwise, everyone has to go and figure them out themselves…

    For Win32Native it looks like:
    using System;
    using System.Runtime.InteropServices;

    For SafeFindHandle:
    using System;
    using System.Runtime.InteropServices;
    using System.Security;
    using Microsoft.Win32.SafeHandles;

    For DirectoryExtensions:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.IO;
    using System.Runtime.InteropServices;
    using Microsoft.Win32;

    — T.J.