1

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.

nhouser9
  • 6,730
  • 3
  • 21
  • 42
  • 1
    Try writing to the key you actually want to write to. I doubt it's possible to pollute the root of HKLM. – Blorgbeard Aug 23 '16 at 23:52
  • @Blorgbeard I have tried it. It does not work. I edited with the key I want to actually write to. It is SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon. – nhouser9 Aug 24 '16 at 00:00
  • 1
    You are surely conflating two different problems. Writing to that key you *actually* want to write to [requires UAC elevation](http://stackoverflow.com/questions/2818179/how-do-i-force-my-net-application-to-run-as-administrator) *and* running your program [as a 64-bit process](http://stackoverflow.com/a/2843835/17034). – Hans Passant Aug 24 '16 at 00:06
  • @HansPassant I have been running it as an admin so UAC elevation shouldn't be the issue. I will look into the 64 bit process link. – nhouser9 Aug 24 '16 at 00:08
  • 1
    @HansPassant The 64 bit process link solved my problem. Feel free to post as an answer if you want the rep. Thanks a ton! – nhouser9 Aug 24 '16 at 00:17

1 Answers1

1

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();
Boinst
  • 3,365
  • 2
  • 38
  • 60