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?
The directory or a file in it is locked and cannot be deleted. Find the culprit who locks it and see if you can eliminate it.
Non of above solutions worked well for me. I ended up by using an edited version of @ryascl solution as below:
I had the very same problem under Delphi. And the end result was that my own application was locking the directory I wanted to delete. Somehow the directory got locked when I was writing to it (some temporary files).
The catch 22 was, I made a simple change directory to it's parent before deleting it.
None of the above answers worked for me. It appears that my own app's usage of
DirectoryInfo
on the target directory was causing it to remain locked.Forcing garbage collection appeared to resolve the issue, but not right away. A few attempts to delete where required.
Note the
Directory.Exists
as it can disappear after an exception. I don't know why the delete for me was delayed (Windows 7 SP1)I have spent few hours to solve this problem and other exceptions with deleting the directory. This is my solution
This code has the small delay, which is not important for my application. But be careful, the delay may be a problem for you if you have a lot of subdirectories inside the directory you want to delete.
As mentioned above the "accepted" solution fails on reparse points - yet people still mark it up(???). There's a much shorter solution that properly replicates the functionality:
I know, doesn't handle the permissions cases mentioned later, but for all intents and purposes FAR BETTER provides the expected functionality of the original/stock Directory.Delete() - and with a lot less code too.
You can safely carry on processing because the old dir will be out of the way ...even if not gone because the 'file system is still catching up' (or whatever excuse MS gave for providing a broken function).
As a benefit, if you know your target directory is large/deep and don't want to wait (or bother with exceptions) the last line can be replaced with:
You are still safe to carry on working.