What is the best way to empty a directory?

2019-06-18 23:44发布

问题:

Is there a way to delete all files & sub-directories of a specified directory without iterating over them?

The non elegant solution:

public static void EmptyDirectory(string path)
{
    if (Directory.Exists(path))
    {
        // Delete all files
        foreach (var file in Directory.GetFiles(path))
        {
            File.Delete(file);
        }

        // Delete all folders
        foreach (var directory in Directory.GetDirectories(path))
        {
            Directory.Delete(directory, true);
        }
    }
}

回答1:

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();
}


回答2:

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



回答3:

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.