How to quickly check if folder is empty (.NET)?

There is a new feature in Directory and DirectoryInfo in .NET 4 that allows them to return an IEnumerable instead of an array, and start returning results before reading all the directory contents.

  • What’s New in the BCL in .NET 4 Beta 1
  • Directory.EnumerateFileSystemEntries method overloads
public bool IsDirectoryEmpty(string path)
{
    IEnumerable<string> items = Directory.EnumerateFileSystemEntries(path);
    using (IEnumerator<string> en = items.GetEnumerator())
    {
        return !en.MoveNext();
    }
}

EDIT: seeing that answer again, I realize this code can be made much simpler…

public bool IsDirectoryEmpty(string path)
{
    return !Directory.EnumerateFileSystemEntries(path).Any();
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)