LykosAI/StabilityMatrix · error · IOException

Failed to delete directory

Error message

Failed to delete directory {directory}

What it means

This is the final stage of DeleteVerbose: after recursively clearing subdirectories and files, the directory itself is deleted with directory.Delete(false), and an IOException is wrapped with the directory path. It means the (now supposedly empty) directory could not be removed by the OS.

Solutions

  1. Ensure no process has its working directory set inside the target directory before deleting
  2. Retry the delete after a short delay to allow OS handle release (common on Windows)
  3. Check for files recreated between enumeration and deletion (race), and re-run the delete
  4. Inspect the inner exception for the exact Win32 error code

Example fix

// before
directory.Delete(false);
// after
for (var attempt = 0; attempt < 3; attempt++)
{
    try { directory.Delete(false); break; }
    catch (IOException) when (attempt < 2) { Thread.Sleep(200); }
}
Defensive patterns

Strategy: retry

Validate before calling

if (Directory.Exists(dir))
{
    if (Path.GetFullPath(dir) == Path.GetFullPath(Directory.GetCurrentDirectory()))
        Directory.SetCurrentDirectory(Path.GetDirectoryName(dir)!);
    if (Directory.EnumerateFileSystemEntries(dir).Any())
        Console.WriteLine("Directory not empty; rerun recursive delete first");
}

Try / catch

try { DirectoryPathExtensions.DeleteVerbose(dir, logger, ct); }
catch (IOException ex)
{
    await Task.Delay(300);
    DirectoryPathExtensions.DeleteVerbose(dir, logger, ct); // single retry after handle release
}

Prevention

When it happens

Trigger: The leaf/parent directory delete throws IOException — typically because the directory is not actually empty (a race added files), the process cwd or a handle is inside it, or an OS-level I/O error occurred.

Common situations: Deleting a package install directory while the application's working directory is set to it; a background process recreating files mid-delete; Windows delayed file-handle release right after deleting children.

Related errors


AI-assisted analysis of LykosAI/StabilityMatrix@af93d6ef57 (2026-09-12). Data as JSON: /api/errors/c21d3a0e13aa0b3f. Report an issue: GitHub.

Appendix: source

Thrown at StabilityMatrix.Core/Extensions/DirectoryPathExtensions.cs:104

            try
            {
                filePath.Info.Attributes = FileAttributes.Normal;
                filePath.Delete();
            }
            catch (IOException ex)
            {
                throw new IOException($"Failed to delete file {filePath.FullPath}", ex);
            }
        }

        // Delete this directory
        try
        {
            directory.Delete(false);
        }
        catch (IOException ex)
        {
            throw new IOException($"Failed to delete directory {directory}", ex);
        }
    }
}

View on GitHub (pinned to af93d6ef57)