I’m trying to read the registry key “RPSessionInterval” from the subkey “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore” in C#. I’m using the following code and getting the exception “Object reference not set to an instance of an object.”
string systemRestore = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore";
RegistryKey baseRegistryKey = Registry.LocalMachine;
public string SystemRestoreStatus(string subKey, string keyName)
{
RegistryKey rkSubKey = baseRegistryKey.OpenSubKey(systemRestore);
if (rkSubKey != null)
{
try
{
string sysRestore = rkSubKey.GetValue("RPSessionInterval").ToString();
if (string.Compare(sysRestore, "1") == 0)
{
MessageBox.Show("System Restore is Enabled!");
return "System Restore is Enabled!";
}
else if (string.Compare(sysRestore, "0") == 0)
{
MessageBox.Show("System Restore is Disabled!");
return "System Restore is Disabled!";
}
else
{
return null;
}
}
catch (Exception ex) //This exception is thrown
{
MessageBox.Show("Error while reading registry key: " + subKey + "\\" + keyName + ". ErrorMessage: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
else
{
MessageBox.Show("Error while reading registry key: " + subKey + "\\" + keyName + " does not exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
Here is a picture showing that the registry key actually exists:

You probably have the wrong bitness for your C# application. By default, a Visual Studio 2010 C# project will compile to x86 (32-bit). A 32-bit application running on a 64-bit OS can generally only access the 32-bit registry, the contents of which are often different than the native 64-bit registry. Change the architecture to “Any CPU” or “x64” and it may work.