{"record":{"id":"29dc8f4ce4ad0f1c","repo":"xM4ddy/OFGB","slug":"ofgb-failed-to-create-subkey-during-initialization","errorCode":null,"errorMessage":"OFGB: Failed to create subkey during initialization!","messagePattern":"OFGB: Failed to create subkey during initialization!","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"critical","filePath":"MainWindow.xaml.cs","lineNumber":112,"sourceCode":"        private static bool CreateKey(string loc, string key)\n        {\n            RegistryKey? keyRef;\n            bool value;\n\n            if (Registry.CurrentUser.OpenSubKey(loc, true) is not null)\n            {\n                keyRef = Registry.CurrentUser.OpenSubKey(loc, true);\n            }\n            else\n            {\n                keyRef = Registry.CurrentUser.CreateSubKey(loc);\n                keyRef.SetValue(key, 0);\n            }\n\n            if (keyRef is null)\n            {\n                MessageBox.Show(\"Failed to create a registry subkey during initialization!\", \"OFGB: Fatal Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n                throw new InvalidOperationException(\"OFGB: Failed to create subkey during initialization!\");\n            }\n\n            value = Convert.ToBoolean(keyRef.GetValue(key));\n            keyRef.Close();\n\n            return value;\n        }\n\n        private static void ToggleOptions(string checkboxName, bool enable)\n        {\n            switch (checkboxName)\n            {\n                case \"cb1\":\n                    Registry.SetValue(\"HKEY_CURRENT_USER\\\\\" + cur_ver + \"Explorer\\\\Advanced\\\\\", \"ShowSyncProviderNotifications\", Convert.ToInt32(!enable));\n                    break;\n                case \"cb2\":\n                    Registry.SetValue(\"HKEY_CURRENT_USER\\\\\" + cur_ver + \"ContentDeliveryManager\", \"RotatingLockScreenOverlayEnabled\", Convert.ToInt32(!enable));\n                    Registry.SetValue(\"HKEY_CURRENT_USER\\\\\" + cur_ver + \"ContentDeliveryManager\", \"SubscribedContent-338387Enabled\", Convert.ToInt32(!enable));","sourceCodeStart":94,"sourceCodeEnd":130,"githubUrl":"https://github.com/xM4ddy/OFGB/blob/a2f3ecf6a51f394eb86113076ee9400db714db71/MainWindow.xaml.cs#L94-L130","documentation":"OFGB (One Free Gadget's Buddy, a Windows telemetry-debloat utility) throws this InvalidOperationException in CreateKey (MainWindow.xaml.cs:112) when it cannot open or create the required HKCU registry subkey during window initialization. In the source, keyRef is only null when both OpenSubKey(loc, true) and CreateSubKey(loc) fail; note that in practice CreateSubKey throws RegistryException rather than returning null, so this guard is a defensive invariant check, but when it fires the app cannot read/write the Windows privacy settings it manages and aborts startup after showing a fatal-error MessageBox. It means the app cannot touch HKEY_CURRENT_USER, so none of the telemetry toggles can be initialized or applied.","triggerScenarios":"CreateKey(loc, key) is called for each telemetry setting (key1..key6 include ContentDeliveryManager, UserProfileEngagement, AdvertisingInfo, Privacy, Explorer\\Advanced, Notifications\\Settings paths); the error surfaces when Registry.CurrentUser.OpenSubKey(loc, true) returns null AND Registry.CurrentUser.CreateSubKey(loc) yields no usable key — i.e., HKCU access is unavailable or the key path cannot be created/opened with write access.","commonSituations":"Running OFGB on a non-Windows platform (e.g., .NET on Linux/macOS where Microsoft.Win32.Registry throws or registry APIs are unavailable); running with a corrupted or locked HKCU hive; the app launched in a restricted sandbox/containers or with group policy restrictions on HKCU\\Software; antivirus or registry permissions blocking writes; a race/TOCTOU where the key is deleted between OpenSubKey and use; a disposed CurrentUser base key in odd hosting scenarios.","solutions":["Run the app on Windows as the interactive user whose HKCU hive is loaded (not as SYSTEM/scheduled task without a user profile) so Registry.CurrentUser maps to a real hive.","Verify registry access manually: in regedit or `reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\ContentDeliveryManager\"` confirm the path exists and is writable; if permissions are wrong, fix ACLs on HKCU\\Software or recreate the user profile.","Check that no policy, antivirus, or AppLocker rule blocks writes under HKCU\\Software\\Policies\\Microsoft and ContentDeliveryManager; temporarily disable AV filtering to test.","If running on non-Windows (cross-platform .NET), guard with OperatingSystem.IsWindows() before calling CreateKey, since Microsoft.Win32.Registry is Windows-only and fails otherwise.","Wrap CreateSubKey calls in try/catch (UnauthorizedAccessException / SecurityException / IOException) and surface a clearer message instead of the generic null-check throw."],"exampleFix":"// before\nkeyRef = Registry.CurrentUser.CreateSubKey(loc);\nkeyRef.SetValue(key, 0);\nif (keyRef is null)\n{\n    throw new InvalidOperationException(\"OFGB: Failed to create subkey during initialization!\");\n}\n// after\nif (!OperatingSystem.IsWindows())\n{\n    MessageBox.Show(\"OFGB only supports Windows.\", \"OFGB: Fatal Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n    throw new PlatformNotSupportedException(\"OFGB requires Windows registry access.\");\n}\ntry\n{\n    keyRef = Registry.CurrentUser.OpenSubKey(loc, true) ?? Registry.CurrentUser.CreateSubKey(loc);\n    keyRef.SetValue(key, 0);\n}\ncatch (Exception ex) when (ex is UnauthorizedAccessException or SecurityException or IOException)\n{\n    MessageBox.Show($\"Cannot access HKCU\\\\{loc}: {ex.Message}\", \"OFGB: Fatal Error\", MessageBoxButton.OK, MessageBoxImage.Error);\n    throw new InvalidOperationException(\"OFGB: Failed to create subkey during initialization!\", ex);\n}","handlingStrategy":"try-catch","validationCode":"// Pre-check before calling CreateKey\nbool canWrite = OperatingSystem.IsWindows();\nif (canWrite)\n{\n    try\n    {\n        using var probe = Registry.CurrentUser.CreateSubKey(\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\ContentDeliveryManager\", writable: true);\n        canWrite = probe is not null;\n    }\n    catch { canWrite = false; }\n}\nif (!canWrite) { /* show fatal message / abort init */ }","typeGuard":"// Narrow the nullable RegistryKey before use\nstatic bool TryOpenWritableKey(string loc, out RegistryKey key)\n{\n    var k = Registry.CurrentUser.OpenSubKey(loc, true) ?? Registry.CurrentUser.CreateSubKey(loc);\n    if (k is null) { key = null!; return false; }\n    key = k; return true;\n}","tryCatchPattern":"try\n{\n    bool value = CreateKey(loc, key);\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"Failed to create subkey\"))\n{\n    // Registry unavailable: degrade gracefully — disable the UI toggles\n    // and log ex.Message instead of crashing the app.\n}\ncatch (UnauthorizedAccessException ex)\n{\n    // Hint the user to run as the regular interactive user / fix HKCU ACLs.\n}","preventionTips":["Run OFGB as the logged-in desktop user, not as a service or under an account without a loaded user profile.","Check Windows platform (OperatingSystem.IsWindows()) before any registry call when hosting on non-Windows .NET.","Keep antivirus/policy software from blocking writes under HKCU\\Software\\Microsoft and HKCU\\Software\\Policies.","Test registry writability once at startup and disable dependent toggles instead of throwing per-key.","Wrap CreateSubKey/OpenSubKey in try/catch so registry exceptions produce actionable messages rather than the generic invariant throw."],"tags":["windows","registry","startup","permissions","csharp"],"backgroundTag":"permission-denied","analyzedSha":"a2f3ecf6a51f394eb86113076ee9400db714db71","analyzedAt":"2026-09-14T11:21:31.999Z","contentChangedAt":"2026-09-14T11:21:31.999Z","schemaVersion":2},"datasetVersion":"2026-09-15T23:17:13.987Z"}