{"record":{"id":"2621f2101ddc3546","repo":"memstechtips/Winhance","slug":"could-not-clear-existing-working-directory-clean","errorCode":null,"errorMessage":"Could not clear existing working directory: {cleanupEx.Message}","messagePattern":"Could not clear existing working directory: (.+?)","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Winhance.Infrastructure/Features/AdvancedTools/Services/IsoService.cs","lineNumber":135,"sourceCode":"                            \"It may be open in Windows Explorer or being used by another process. \" +\r\n                            \"Please close it or delete it manually and try again.\"\r\n                        );\r\n                    }\r\n\r\n                    _logService.LogInformation(\"Working directory cleared successfully\");\r\n                }\r\n                catch (OperationCanceledException)\r\n                {\r\n                    throw;\r\n                }\r\n                catch (InvalidOperationException)\r\n                {\r\n                    throw;\r\n                }\r\n                catch (Exception cleanupEx)\r\n                {\r\n                    _logService.LogError($\"Failed to clear working directory: {cleanupEx.Message}\", cleanupEx);\r\n                    throw new InvalidOperationException($\"Could not clear existing working directory: {cleanupEx.Message}\", cleanupEx);\r\n                }\r\n            }\r\n\r\n            _fileSystemService.CreateDirectory(workingDirectory);\r\n\r\n            progress?.Report(new TaskProgressDetail\r\n            {\r\n                StatusText = _localization.GetString(\"Progress_MountingIso\"),\r\n                TerminalOutput = $\"ISO: {isoPath}\"\r\n            });\r\n\r\n            _logService.LogInformation($\"Mounting ISO: {isoPath}\");\r\n\r\n            var mountResult = await _processExecutor.ExecuteAsync(\r\n                \"powershell.exe\",\r\n                $\"-NoProfile -Command \\\"(Mount-DiskImage -ImagePath '{isoPath}' -PassThru | Get-Volume).DriveLetter\\\"\",\r\n                cancellationToken).ConfigureAwait(false);\r\n            var rawOutput = mountResult.StandardOutput;\r","sourceCodeStart":117,"sourceCodeEnd":153,"githubUrl":"https://github.com/memstechtips/Winhance/blob/f23d554eb2d6400b1827bcc46b91294ffa53fbc9/src/Winhance.Infrastructure/Features/AdvancedTools/Services/IsoService.cs#L117-L153","documentation":"The catch-all around the working-directory cleanup block in IsoService. Any exception that is not OperationCanceledException or the explicit InvalidOperationException from error [0] is rewrapped as a new InvalidOperationException with the original message. Its real value is preserving the inner exception via the `cleanupEx` constructor argument so the stack trace is not lost.","triggerScenarios":"An unexpected exception type escapes the inner try during cleanup — e.g. Remove-Item throws a PowerShell process-launch failure, _processExecutor.ExecuteAsync throws IOException, the cancellation token surfaces as a non-OCE exception, or DirectoryExists itself throws UnauthorizedAccessException.","commonSituations":"powershell.exe is not on PATH or is blocked by policy. The file system abstraction throws on a transient I/O error. A third-party shell replacement interferes with launching powershell.exe. A bug in a downstream service throws an exception type the author did not anticipate.","solutions":["Inspect the InnerException (and the log line just before the throw) to find the real cause — the wrapper message only echoes cleanupEx.Message.","If powershell.exe launch failed, verify PowerShell is installed and not blocked by group policy, then retry.","Reproduce with verbose logging enabled to capture the full stack of the inner exception.","Treat the cleanup as best-effort: consider relaxing the outer caller so a cleanup failure does not abort the entire ISO workflow when the directory can be recreated fresh."],"exampleFix":"// before: blanket rewrap that hides the original type\nthrow new InvalidOperationException($\"Could not clear existing working directory: {cleanupEx.Message}\", cleanupEx);\n\n// after: keep the original exception type when it is already actionable, only wrap unknowns\nif (cleanupEx is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception)\n    throw; // callers already know how to handle these\nthrow new InvalidOperationException($\"Could not clear existing working directory: {cleanupEx.Message}\", cleanupEx);","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"catch (InvalidOperationException ex) when (ex.Message.StartsWith(\"Could not clear existing working directory\"))\n{\n    // Inspect ex.InnerException for the real cause; report InnerException.GetType().Name + Message to the user.\n    // Do not retry blindly — the inner exception determines whether a retry is safe.\n}","preventionTips":["Always read InnerException on these wrapped errors — the message is just the inner one.","Enable verbose logging so the original stack is captured before rewrapping.","Treat working-directory cleanup as best-effort where possible so a transient failure does not abort the workflow."],"tags":["exception-wrapping","cleanup","io","diagnostics"],"backgroundTag":null,"analyzedSha":"f23d554eb2d6400b1827bcc46b91294ffa53fbc9","analyzedAt":"2026-08-13T17:55:20.922Z","schemaVersion":2},"datasetVersion":"2026-08-13T19:17:28.613Z"}