Murugan
Murugan

Reputation: 13

How to create registry key under Computer\HKEY_LOCAL_MACHINE\SOFTWARE\ from C#

I have .net solution which generates build in X86(as target Platform). I am expecting below mentioned registry key entry should be created under Computer\HKEY_LOCAL_MACHINE\SOFTWARE\ FolderName, But it creates entry under Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node which is not expected here. If I change .net solution as X64(Build Target Platform), then it creates under “local machine\Software”

Screenshot

Microsoft.Win32.RegistryKey subKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE");
            if (checkIfKeyExists(subKey))
            {
                subKey =  Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\FolderName");
                if (!checkIfKeyExists(subKey))
                {
                    Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\ FolderName ");
                    Microsoft.Win32.Registry.LocalMachine.SetValue("TestKey", "456788", RegistryValueKind.String);
                }
            }

Upvotes: 1

Views: 1454

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134621

32-bit apps will default to the 32-bit view of the registry. If you want to direct your key accesses to the 64-bit views, you need to open the registry hives manually and not using the Registry class members.

using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
using (var key = hklm.CreateSubKey(@"SOFTWARE\FolderName", writable: true))
{
    // do stuff with the key
    if (key.GetValue("TestKey") == null)
        key.SetValue("TestKey", "456788");
}

Upvotes: 2

Related Questions