I'm using .NET 3.5, trying to recursively delete a directory using:
Directory.Delete(myPath, true);
My understanding is that this should throw if files are in use or there is a permissions problem, but otherwise it should delete the directory and all of its contents.
However, I occasionally get this:
System.IO.IOException: The directory is not empty.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
...
I'm not surprised that the method sometimes throws, but I'm surprised to get this particular message when recursive is true. (I know the directory is not empty.)
Is there a reason I'd see this instead of AccessViolationException?
Modern Async Answer
The accepted answer is just plain wrong, it might work for some people because the time taken to get files from disk frees up whatever was locking the files. The fact is, this happens because files get locked by some other process/stream/action. The other answers use
Thread.Sleep
(Yuck) to retry deleting the directory after some time. This question needs revisiting with a more modern answer.Unit Tests
These tests show an example of how a locked file can cause the
Directory.Delete
to fail and how theTryDeleteDirectory
method above fixes the problem.This problem can appear on Windows when there are files in a directory (or in any subdirectory) which path length is greater than 260 symbols.
In such cases you need to delete
\\\\?\C:\mydir
instead ofC:\mydir
. About the 260 symbols limit you can read here.add true in the second param.
It will remove all.
It appears that having the path or subfolder selected in Windows Explorer is enough to block a single execution of Directory.Delete(path, true), throwing an IOException as described above and dying instead of booting Windows Explorer out to a parent folder and proceding as expected.
I had a those weird permission problems deleting User Profile directories (in C:\Documents and Settings) despite being able to do so in the Explorer shell.
It makes no sense to me what a "file" operation does on a directory, but I know that it works and that's enough for me!
Recursive directory deletion that does not delete files is certainly unexpected. My fix for that:
I experienced cases where this helped, but generally, Directory.Delete deletes files inside directories upon recursive deletion, as documented in msdn.
From time to time I encounter this irregular behavior also as a user of Windows Explorer: Sometimes I cannot delete a folder (it think the nonsensical message is "access denied") but when I drill down and delete lower items I can then delete the upper items as well. So I guess the code above deals with an OS anomaly - not with a base class library issue.