views:

136

answers:

6

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  A: 

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

Tommy Carlier
+7  A: 

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 :)

After re-interpreting your question, this is the best I've got:

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();
}
BlueMonkMN
That's a nice solution, but I don't see how it's more elegant than the original code. I just don't understand what the problem is.
Tommy Carlier
A: 

One possible way is to call system command interpreter.

Mad Fish
+1  A: 

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.

DannySmurf
If I interpret his post correctly, he doesn't want to delete the directory, just the files and sub-directories in it.
Tommy Carlier
Yeh, true, but Directory.Delete is still the best way. Deleting the directory and recreating an empty one in its place is more "elegant" and probably faster than iteration.
DannySmurf
A: 

This looks like a good solution to me. I'm not sure how much "more elegant" it can get. What issues exactly do you have with this solution?

Cody C
A: 

Delete the directory with the recursive call mentioned, and create a new directory with the same name. :)

Oskar