What is the best way to empty a directory?

How about System.IO.Directory.Delete? It has a recursion option, you're even using it. Reviewing your code it looks like you're trying to do something slightly different -- empty the directory without deleting it, right? Well, you could delete it and re-create it :)


In any case, you (or some method you use) must iterate over all of the files and subdirectories. However, you can iterate over both files and directories at the same time, using GetFileSystemInfos:

foreach(System.IO.FileSystemInfo fsi in 
    new System.IO.DirectoryInfo(path).GetFileSystemInfos())
{
    if (fsi is System.IO.DirectoryInfo)
        ((System.IO.DirectoryInfo)fsi).Delete(true);
    else
        fsi.Delete();
}

Why is that not elegant? It's clean, very readable and does the job.


Well, you could always just use Directory.Delete....

http://msdn.microsoft.com/en-us/library/aa328748%28VS.71%29.aspx

Or if you want to get fancy, use WMI to delete the directory.