Home > OS >  Why is the Registry Key showing null in C# even if it is present in Registry Editor?
Why is the Registry Key showing null in C# even if it is present in Registry Editor?

Time:10-28

Here is my c# code:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile",  true))
{
    key.CreateSubKey("NetworkThrottlingIndex");
    key.SetValue("NetworkThrottlingIndex", "0000000a", RegistryValueKind.DWord);
    key.CreateSubKey("SystemResponsiveness");
    key.SetValue("SystemResponsiveness", "00000000", RegistryValueKind.DWord);
    key.CreateSubKey("NoLazyMode");
    key.SetValue("NoLazyMode", "1");
}

So what is happening here is that I am getting an error

System.NullReferenceException

on the line

key.CreateSubKey("NetworkThrottlingIndex");

because the key is null.

I checked several times but this key is present in my registry editor.

Any idea about what is wrong here?

CodePudding user response:

The SOFTWARE registry key is redirected depending on the bitness of your application and Windows.

To access your key via a x86/32bit EXE (on 64 bit Windows) request the 64 bit Registry View:

using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
using (var key = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile", RegistryKeyPermissionCheck.ReadWriteSubTree))
{
   ...
}

Also note that NetworkThrottlingIndex is a sub-key (i.e. a "Folder") and thus you cannot set its value as it has none. Additionally you would use hex literals for the DWORD values (0x0000000a) rather that strings.

  • Related