{"record":{"id":"a7301b2d738a9f37","repo":"itsfatduck/optimizerDuck","slug":"failed-to-create-registry-key-root-name-currentpath","errorCode":null,"errorMessage":"Failed to create registry key: {root.Name}\\{currentPath}","messagePattern":"Failed to create registry key: (.+?)\\\\(.+?)","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"optimizerDuck/Services/Optimization/Providers/RegistryService.cs","lineNumber":981,"sourceCode":"    {\n        var parts = subPath.Split('\\\\', StringSplitOptions.RemoveEmptyEntries);\n\n        var current = root;\n        var ownsCurrent = false;\n        var currentPath = string.Empty;\n\n        try\n        {\n            foreach (var part in parts)\n            {\n                currentPath = currentPath.Length == 0 ? part : $\"{currentPath}\\\\{part}\";\n\n                var next = current.OpenSubKey(part, true);\n                if (next == null)\n                {\n                    next =\n                        current.CreateSubKey(part, true)\n                        ?? throw new InvalidOperationException(\n                            $\"Failed to create registry key: {root.Name}\\\\{currentPath}\"\n                        );\n\n                    createdSubKeys.Add($\"{root.Name}\\\\{currentPath}\");\n                    logger?.LogDebug(\n                        \"Created registry subkey: {Path}\",\n                        $\"{root.Name}\\\\{currentPath}\"\n                    );\n                }\n\n                // dispose old key if we opened it\n                if (ownsCurrent)\n                    current.Dispose();\n\n                current = next;\n                ownsCurrent = true;\n            }\n","sourceCodeStart":963,"sourceCodeEnd":999,"githubUrl":"https://github.com/itsfatduck/optimizerDuck/blob/36acf585ae122a09f0e29eb4acedfaf94e81c0de/optimizerDuck/Services/Optimization/Providers/RegistryService.cs#L963-L999","documentation":"RegistryService.CreateSubKeyTrack throws InvalidOperationException when RegistryKey.CreateSubKey(part, true) returns null while walking/creating the key path segment by segment. CreateSubKey returning null means Windows refused to create the key — almost always because the parent is not writable or the path depth is invalid, despite the operation normally creating-or-opening.","triggerScenarios":"Creating a missing subkey during apply (e.g. writing a value into a key tree that does not exist) where the intermediate key cannot be created: parent opened without write access (HKLM without elevation), key protected by ACL/WRP, or a path part empty/invalid length (exceeds 255 chars per key name).","commonSituations":"Running the app unelevated and optimizing an HKLM setting; Windows Resource Protection guarding system keys; corporate policy ACLs denying write; extremely long optimization registry paths hitting the key-name limit.","solutions":["Run the app as administrator (app.manifest requires it — confirm the process is actually elevated).","Check the key's ACLs in regedit (Permissions) and take ownership/adjust if a policy locked it.","Verify the registry path in the optimization definition for empty segments or invalid characters/length.","If Windows protects the key (WRP), skip the optimization — it is not applicable on that system."],"exampleFix":"// before\nnext = current.CreateSubKey(part, true) ?? throw ...;\n// after (guard writability first)\nif (!root.CanWrite)\n    throw new InvalidOperationException($\"Registry hive not writable (elevation required): {root.Name}\");\nnext = current.CreateSubKey(part, true) ?? throw ...;","handlingStrategy":"try-catch","validationCode":"using var probe = Registry.LocalMachine.OpenSubKey(subPath);\nbool writable = probe != null &&\n    (new RegistrySecurity()).Equals(null) is false; // simpler: attempt CreateSubKey in try/catch","typeGuard":"static bool HiveWritable(RegistryKey root) =>\n    Environment.IsPrivilegedProcess;","tryCatchPattern":"try { registryService.CreateSubKey(path, opCall); }\ncatch (InvalidOperationException ex) when (ex.Message.StartsWith(\"Failed to create registry key\"))\n{ logger.LogError(\"Elevation or ACLs blocked key creation: {Msg}\", ex.Message); }","preventionTips":["Always run the app elevated (requireAdministrator)","Avoid targeting WRP-protected keys; gate those optimizations with conditions","Validate registry paths in optimization definitions (no empty/oversized segments)","Prefer HKCU for per-user tweaks instead of forcing HKLM"],"tags":["csharp","registry","windows","permissions"],"backgroundTag":"permission-denied","analyzedSha":"36acf585ae122a09f0e29eb4acedfaf94e81c0de","analyzedAt":"2026-09-13T08:30:13.845Z","contentChangedAt":"2026-09-13T08:30:13.845Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}