Search code examples
c#registrykey

Registry.LocalMachine.CreateSubKey: Parameter Invalid


Is it possible to create directly under HKEY_LOCAL_MACHINE aside from HARDWARE, SAM, SECURITY, SOFTWARE, etc.. using C#? I've tried the following code, but I'm getting an error:

RegistryKey key = Registry.LocalMachine.CreateSubKey("TESTFOLDER", RegistryKeyPermissionCheck.Default, RegistryOptions.None);

The error states:

Parameter invalid

I've already tried executing my application as an administrator.


Solution

  • The registry contains a mixture of elements. Many parts of the registry have files which store them when the operating system isn't running - these are described under the help for Registry Hives

    There you'll see that HKEY_LOCAL_MACHINE doesn't have a hive file. Several keys under it, such as Sam and Software have individual hive files. Others, such as Hardware do not. This is logical - HKEY_LOCAL_MACHINE\Hardware is recreated anew each time the OS boots.

    In turn, HKEY_LOCAL_MACHINE is also created anew each time the OS boots and then attaches subkeys, some coming from Hive files, some having been created.

    You cannot create a new subkey under HKEY_LOCAL_MACHINE because the OS doesn't have anywhere to store it (it's not backed by a Hive itself) nor have any knowledge to recreate it the next time it boots.