Search code examples
c#registry

C# editing Registry does not work


I am trying to do some registry editing. The below code is a MCVE of my problem:

        RegistryKey key;
        key = Registry.LocalMachine.OpenSubKey("DRIVERS", true);
        key = key.CreateSubKey("Names");
        key.SetValue("Name", "nick", RegistryValueKind.String);
        key.Close();

That code works fine. The following (changed DRIVERS to SOFTWARE) does not:

        RegistryKey key;
        key = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
        key = key.CreateSubKey("Names");
        key.SetValue("Name", "nick", RegistryValueKind.String);
        key.Close();

To me, the difference between the two blocks of code is trivial. What is the cause of this issue, and how can I get around it? I am already running the code as an admin.

My end goal is to modify the values in the "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" folder.

I know this is possible from Powershell - it should be possible from C# as well.


Solution

  • You can write to the 64-bit registry from a 32-bit process, but you need to explicitly request the 64-bit registry as follows (modified from your code in the Q).

    var hklm = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
    RegistryKey key = hklm.OpenSubKey("SOFTWARE", true);
    key = key.CreateSubKey("Names");
    key.SetValue("Name", "nick", RegistryValueKind.String);
    key.Close();