Search code examples
c#.netregistry

Reading registry value crashes


My below code fails no matter if I run it as Administrator or not:

var suff = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\CCM\\LocationServices", true);
var value = suff.GetValue("DnsSuffix").ToString();

I get this error message which I can't decode:

An unhandled exception of type 'System.NullReferenceException' occurred in MyApp.exe Additional information: Object reference not set to an instance of an object.

I know for a fact that the value exists and it contains data as well.

*Edit: So like I said it shouldn't be null as the data exists. And if it is null then I will need to know why is it null. Therefore, a question regarding what is System.NullReferenceException won't help me at all.


Solution

  • As raj's answer pointed out in this SO question, which is similar to yours, the problem could be that you're opening the registry on a 64bits OS.

    Try this approach instead (.NET 4.0 or later) :

    public class HKLMRegistryHelper
    {
    
        public static RegistryKey GetRegistryKey()
        {
            return GetRegistryKey(null);
        }
    
        public static RegistryKey GetRegistryKey(string keyPath)
        {
            RegistryKey localMachineRegistry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32);
    
            return string.IsNullOrEmpty(keyPath) ? localMachineRegistry : localMachineRegistry.OpenSubKey(keyPath);
        }
    
        public static object GetRegistryValue(string keyPath, string keyName)
        {
            RegistryKey registry = GetRegistryKey(keyPath);
            return registry.GetValue(keyName);
        }
    }
    

    ... and replace your code with :

    string keyPath = @"SOFTWARE\Microsoft\CCM\LocationServices";
    string keyName = "DnsSuffix";
    
    var value = HKLMRegistryHelper.GetRegistryValue(keyPath, keyName);