How quickly check the directory on the emptiness?

  • Thread starter Alexander Vasilevsky
  • Start date
J

Jeroen Mostert

Alexander said:
How quickly check the directory on the emptiness?
Faster than System.IO.Directory.GetFiles().
There isn't really an intrisically fast way of doing this (in the sense that
there's no easily readable property for a directory that will tell you it's
empty). That said, you can probably improve the time from linear to constant
by P/Invoking to FindFirstFile()/FindNextFile()/FindClose(). If the
directory is empty, FindFirstFile() will only find the entry for the
directory itself (".") and FindNextFile() will fail with
ERROR_FILE_NOT_FOUND. This means you can stop the search right there,
without getting a list of all files like .GetFiles() does.

As a disclaimer to this: I don't know whether FindFirstFile()/FindNextFile()
operate in (semi-)constant time when the directory is not empty; I've never
tested it.

Note that any technique of this kind is subject to a failure condition where
another application creates or removes files after you check the directory
for emptiness but before you have a chance to act on that information. This
isn't usually important, but worth considering nonetheless.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top