memstechtips/Winhance · error · InvalidOperationException

Could not delete the existing working directory '{workingDir

Error message

Could not delete the existing working directory '{workingDirectory}'. It may be open in Windows Explorer or being used by another process. Please close it or delete it manually and try again.

What it means

Thrown by IsoService after a PowerShell Remove-Item -Recurse -Force call failed to actually remove the ISO working directory — the post-deletion DirectoryExists check still returns true. This is not a normal cleanup failure: Remove-Item ran with -ErrorAction Stop but the directory survived, so the code treats the working directory as locked and refuses to proceed with ISO creation over a stale tree.

Source

Thrown at src/Winhance.Infrastructure/Features/AdvancedTools/Services/IsoService.cs:115

                _logService.LogInformation($"Clearing existing working directory: {workingDirectory}");

                try
                {
                    var script = $@"
                        Get-ChildItem -Path '{workingDirectory}' -Recurse -Force | ForEach-Object {{ $_.Attributes = 'Normal' }}
                        Remove-Item -Path '{workingDirectory}' -Recurse -Force -ErrorAction Stop
                    ";

                    var removeResult = await _processExecutor.ExecuteAsync(
                        "powershell.exe",
                        $"-NoProfile -ExecutionPolicy Bypass -Command \"{script}\"",
                        cancellationToken).ConfigureAwait(false);
                    var errorOutput = removeResult.StandardError;

                    if (_fileSystemService.DirectoryExists(workingDirectory))
                    {
                        _logService.LogError($"Failed to delete working directory. It may be in use by another process: {errorOutput}");
                        throw new InvalidOperationException(
                            $"Could not delete the existing working directory '{workingDirectory}'. " +
                            "It may be open in Windows Explorer or being used by another process. " +
                            "Please close it or delete it manually and try again."
                        );
                    }

                    _logService.LogInformation("Working directory cleared successfully");
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (InvalidOperationException)
                {
                    throw;
                }
                catch (Exception cleanupEx)
                {

View on GitHub (pinned to f23d554eb2)

Solutions

  1. Close Windows Explorer windows showing the working directory and any apps that opened files inside it, then retry the operation.
  2. Manually delete the working directory (%temp% or the configured ISO staging path) via Explorer or an elevated `rmdir /s /q "<path>"`, then retry.
  3. Temporarily disable real-time antivirus scanning on the staging folder, or add it as an exclusion, to prevent handle contention during recursive delete.
  4. Ensure the Winhance process is elevated (run as administrator) so it has delete rights on the full tree.
  5. Check the logged StandardError output from Remove-Item (logged just before the throw) for the exact Win32 reason — it names the offending file and error code.

Example fix

// before: single PowerShell Remove-Item; any sharing violation aborts the whole operation
var script = $"Remove-Item -Path '{workingDirectory}' -Recurse -Force -ErrorAction Stop";

// after: retry loop with backoff, then fall back to renaming the stuck directory aside
for (int attempt = 0; attempt < 3; attempt++)
{
    if (!_fileSystemService.DirectoryExists(workingDirectory)) break;
    await _processExecutor.ExecuteAsync("powershell.exe",
        $"-NoProfile -ExecutionPolicy Bypass -Command \"Remove-Item -Path '{workingDirectory}' -Recurse -Force -ErrorAction Stop\"",
        cancellationToken).ConfigureAwait(false);
    if (!_fileSystemService.DirectoryExists(workingDirectory)) break;
    await Task.Delay(500 * (attempt + 1), cancellationToken).ConfigureAwait(false);
}
if (_fileSystemService.DirectoryExists(workingDirectory))
{
    var sideload = workingDirectory + $".stuck.{DateTime.UtcNow:yyyyMMddHHmmss}";
    _fileSystemService.MoveDirectory(workingDirectory, sideload); // rename aside, continue
    _logService.LogWarning($"Could not delete working dir; moved aside to {sideload}");
}
Defensive patterns

Strategy: retry

Validate before calling

// Before starting ISO creation, probe whether the staging dir is removable.
bool CanClearWorkingDirectory(string dir) =>
    !_fileSystemService.DirectoryExists(dir) || HasExclusiveDeleteAccess(dir);

bool HasExclusiveDeleteAccess(string dir)
{
    try
    {
        foreach (var f in System.IO.Directory.EnumerateFiles(dir, "*", System.IO.SearchOption.AllDirectories))
            using (var fs = new System.IO.FileStream(f, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None)) { }
        return true;
    }
    catch { return false; }
}

Try / catch

catch (InvalidOperationException ex) when (ex.Message.Contains("Could not delete the existing working directory"))
{
    // surfaced to the user with the staging path and a 'close Explorer / delete manually' prompt;
    // offer a retry once the user confirms they freed the handle.
}

Prevention

When it happens

Trigger: Calling the ISO-mount/create flow when a previous working directory already exists and cannot be removed. The directory is open in Windows Explorer, a file handle is held by another process (antivirus, search indexer, a mounted child ISO, or the previous oscdimg run still finishing), or the path requires elevation the current process does not have.

Common situations: A prior ISO creation run crashed or was cancelled, leaving a partial working directory. Antivirus (Windows Defender real-time scan) or the Explorer preview pane holds a handle to a file inside the directory. The directory sits on a network/UNC path or a drive the user lacks delete rights on. A file in the tree is read-only and -Force could not override a sharing violation.

Related errors


AI-assisted analysis of memstechtips/Winhance@f23d554eb2 (2026-08-13). Data as JSON: /api/errors/37e2417789e11223. Report an issue: GitHub.