The Bug
C# has a bug in which it sometimes throws an
IOException
(Message: "The directory is not empty") when attempting to delete a directory with the recursive option set to
True
. This bug typically occurs when the directory being deleted either is open, or has been very recently opened and/or closed. It can also be caused by anti-virus software, or other software that is file-system intensive. These factors all result in Explorer placing a "lock" that it does not have time to release, on the directory being deleted.
The Solution
Although it looks a little silly, the following is the solution to the issue:
try
{
Directory.Delete( path, false );
}
catch ( IOException )
{
Thread.Sleep( 0 );
Directory.Delete( path, false );
}
What is happening is that the system asks Explorer to "release the directory handle", then attempts to delete the directory. If the directory handle was not deleted in time, an exception is raised and the
catch
block is executed (meanwhile, Explorer is still releasing the directory, as no command has been sent to tell it not to do so). The call to
Thread.Sleep(0)
may or may not be necessary (I have not tested this without it), as the
catch
block has already given the system a bit more time, but it does provide a little extra safety for a low cost. After that, the
Delete
is called, again, with the directory already having been released.