Search code examples
c#.netregistryuacregistrykey

Unable to create/write values to Registry subkey despite Admin privileges C#


In my console application, I want to create a DWORD value and set it's value to 2 to my registry sub key in Local machine. Please note, I own Administrator privileges to my machine.

Here's my code below which is getting executed successfully but I am unable to see any value getting set in Registry.

            string keyPathI = @"SOFTWARE\Microsoft\Terminal Server Client";
            string keyPathII = @"SOFTWARE\WOW6432Node\Microsoft\Terminal Server Client";

            RegistryKey keyOne = Registry.LocalMachine.OpenSubKey(keyPathI, true);
            RegistryKey keyTwo = Registry.LocalMachine.OpenSubKey(keyPathII, true);

            if (keyOne != null)
            {
                keyOne.SetValue("RemoteDesktop_SuppressWhenMinimized", 2, RegistryValueKind.DWord);

                keyOne.Close();
            }

            if (keyTwo != null)
            {
                keyTwo.SetValue("RemoteDesktop_SuppressWhenMinimized", 2, RegistryValueKind.DWord);
                keyTwo.Close();
            }

Here's my app.manifest

<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
  <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />              
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

What else I should do to write the values to Registry subkey ?

P.S : Though there are many similar articles on web, I have referred all of them but none of them could help me out.


Solution

  • This works for me (VS 2015, 32-bit app on Windows 64) (test on 64-bit hive)=>

    using (RegistryKey rkLocalMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
    {
        using (RegistryKey rk = rkLocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Terminal Server Client", true))
        {
            rk.SetValue("RemoteDesktop_SuppressWhenMinimized", 2, RegistryValueKind.DWord);
        }
    }