Search code examples
c#registryregistrykey

C# Reading Registry Key/Value, Key is Always NULL


I saw several posts on how to read registry key value on here and I think I am doing it all right but the key I read in my case is always null for some reason.

In HKLM\SOFTWARE, I created key MyCompany and then within that key, I created another key MyApp like: HKLM\SOFTWARE\MyCompany\MyApp

In this key, I added a string string value "MySetting"

I am trying to read that value using following code:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\MyCompany\MyApp", false))
{
    string spaUrl = (String)key.GetValue("MySetting");
}

but the key is always null even though I have these keys and value set at the location above. Any idea what I am doing wrong?

I get

System.NullReferenceException was unhandled exception because key is always null.

SOLUTION

Thanks to Luke Merrett answer below, I modify the location of my keys to be in HKLM\SOFTWARE\WOW6432Node and that worked. Thanks Luke


Solution

  • As Steve indicated, it may be a x86 vs x64 issue. I reproduced your code locally and when running under x86 my key was always null. Changing it to x64 allowed me to access the key.

    You can change the target under Project Properties -> Build here:

    enter image description here

    There's some more detail on this here if you explicitly need an x86 key. Alternatively you can run %systemroot%\syswow64\regedit to add and edit x86 keys.

    For reference; this works both as Admin and running as a standard user