What is the best way to delete a directory?

Is there a way to delete all files and subdirectories of a specified directory without iterating over them?

Not an 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); } } } 
+7
c # filesystems
source share
4 answers

What about System.IO.Directory.Delete? It has a recursion option, you even use it. After looking at your code, it looks like you are trying to do something a little different - clear the directory without deleting it, right? Well, you can delete it and recreate it :)


In any case, you (or any method that you use) must iterate over all files and subdirectories. However, you can iterate over 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(); } 
+10
source share

Why is it not elegant? It is clean, very readable and does the job.

+4
source share

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

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

Or, if you want a fantasy, use WMI to delete the directory.

+2
source share

Here's an extension method based on the original OPs code, which I think is just fine and a bit more readable than other options.

I agree that it would be nice to have one method in the structure for deleting the contents of a directory without deleting the directory, but, in my opinion, this is the next best thing.

 using System; using System.IO; namespace YourNamespace { public static class DirectoryInfoExtensions { public static void EmptyDirectory(this DirectoryInfo di) { if (di.Exists) { foreach (var file in di.GetFiles()) { file.Delete(); } foreach (var directory in di.GetDirectories()) { directory.Delete(true); } } } } } 
0
source share

All Articles