Solving the C# Bug When Recursively Deleting Directories

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:

        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.

Post a Comment

  • Comment by Mark Ursino on Jun 21, 2013
    Is this a known bug that is documented?
    • Comment by Zachary Kniebel on Jun 21, 2013

      Yes and no. The issue occurs in:

      • Directory.Delete(string, bool)
      • Directory.Delete(string)
      • DirectoryInfo.Delete(string, bool)
      • DirectoryInfo.Delete(string)

      All of them mention it as a cause of an IOException in their documentation. However, they state that this should only occur for this reason in XP or earlier. As such, I would classify it as a bug, since it does occur in Windows 7, for all four methods. 

      Side-note: None of the documentation tells you how to resolve the issue. 

  • Comment by knorock on Apr 23, 2021 - cialis prescription online