{"record":{"id":"6ab170de8eae94fe","repo":"LykosAI/StabilityMatrix","slug":"win32exception-native-win32-error-from-marshal","errorCode":null,"errorMessage":"Win32Exception (native Win32 error from Marshal.GetLastWin32Error) during shell item creation","messagePattern":"Win32Exception \\(native Win32 error from Marshal\\.GetLastWin32Error\\) during shell item creation","errorType":"exception","errorClass":"Win32Exception","httpStatus":null,"severity":"error","filePath":"StabilityMatrix.Native.Windows/FileOperations/FileOperationWrapper.cs","lineNumber":173,"sourceCode":"        // Normalize path slashes\n        path = path.Replace('/', '\\\\');\n\n        return new ComReleaser<IShellItem>(\n            (IShellItem)SHCreateItemFromParsingName(path, IntPtr.Zero, ref _shellItemGuid)\n        );\n    }\n\n    private static ComReleaser<IShellItemArray> CreateShellItemArray(params string[] paths)\n    {\n        var pidls = new IntPtr[paths.Length];\n\n        try\n        {\n            for (var i = 0; i < paths.Length; i++)\n            {\n                if (SHParseDisplayName(paths[i], IntPtr.Zero, out var pidl, 0, out _) != 0)\n                {\n                    throw new Win32Exception(Marshal.GetLastWin32Error());\n                }\n\n                pidls[i] = pidl;\n            }\n\n            return new ComReleaser<IShellItemArray>(\n                SHCreateShellItemArrayFromIDLists((uint)pidls.Length, pidls)\n            );\n        }\n        finally\n        {\n            foreach (var pidl in pidls)\n            {\n                Marshal.FreeCoTaskMem(pidl);\n            }\n        }\n    }\n","sourceCodeStart":155,"sourceCodeEnd":191,"githubUrl":"https://github.com/LykosAI/StabilityMatrix/blob/af93d6ef57c01cd890d7e0ad0a9ea8c9fcda3002/StabilityMatrix.Native.Windows/FileOperations/FileOperationWrapper.cs#L155-L191","documentation":"CreateShellItemArray converts filesystem paths to PIDLs via SHParseDisplayName before building an IShellItemArray for Explorer shell operations. If SHParseDisplayName returns a non-zero HRESULT for any path, a Win32Exception built from Marshal.GetLastWin32Error is thrown, indicating Windows could not resolve the path into a shell item.","triggerScenarios":"Calling shell file operations (delete/recycle via the Windows FileOperationWrapper) with a path that fails SHParseDisplayName: nonexistent file, invalid characters, a path on an unavailable drive, or insufficient access.","commonSituations":"Recycling a file that was already deleted by another process; paths with illegal characters or exceeding MAX_PATH on old Windows; network/USB drive disconnected mid-operation; antivirus locking the item.","solutions":["Verify every path passed to the operation exists (File.Exists/Directory.Exists) immediately before the call.","Re-check the path for invalid characters or device/UNC issues and normalize it to a full absolute path.","Confirm the drive/volume hosting the path is mounted and accessible.","Retry the operation; if it persists, run elevated or fall back to a plain (non-shell) delete."],"exampleFix":"// before\nawait fileOps.DeleteItems(new[] { path });\n// after\nif (File.Exists(path) || Directory.Exists(path))\n    await fileOps.DeleteItems(new[] { Path.GetFullPath(path) });","handlingStrategy":"try-catch","validationCode":"var missing = paths.Where(p => !File.Exists(p) && !Directory.Exists(p)).ToList();\nif (missing.Count > 0) throw new FileNotFoundException(\"Paths missing before shell op\", string.Join(\",\", missing));","typeGuard":"static bool IsShellPathUsable(string path) =>\n    !string.IsNullOrWhiteSpace(path) && (File.Exists(path) || Directory.Exists(path)) && path.IndexOfAny(Path.GetInvalidPathChars()) < 0;","tryCatchPattern":"try { await fileOps.DeleteItems(paths); }\ncatch (Win32Exception ex)\n{\n    logger.Warning(ex, \"Shell item creation failed (win32 err {Code})\", ex.NativeErrorCode);\n    // fallback: plain File/Directory delete or retry after re-verifying paths\n}","preventionTips":["Re-verify existence of all paths immediately before shell operations.","Normalize paths to full absolute paths and strip invalid characters.","Handle network/USB volumes being unavailable before operating on them.","Provide a non-shell fallback delete when shell operations fail."],"tags":["windows","shell","win32","filesystem"],"backgroundTag":"file-not-found","analyzedSha":"af93d6ef57c01cd890d7e0ad0a9ea8c9fcda3002","analyzedAt":"2026-09-12T19:02:43.389Z","contentChangedAt":"2026-09-12T19:02:43.389Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}