我试图从C#中的子项“HKLM \ SOFTWARE \微软\的Windows NT \ CurrentVersion \ SystemRestore”读取registry项“RPSessionInterval”。 我正在使用下面的代码并得到exception“对象引用未设置为对象的实例”。
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; } }
这是一张图片,显示registry项实际存在:
你可能对你的C#应用程序有点错误。 默认情况下,Visual Studio 2010 C#项目将编译为x86(32位) 。 在64位操作系统上运行的32位应用程序通常只能访问32位注册表, 其内容通常与本机64位注册表不同 。 更改体系结构为“任何CPU”或“x64” ,它可能会工作。
对于SystemRestoreStatus的调用,您最有可能遇到拼写问题,该问题导致以下行中的异常:
string sysRestore = rkSubKey.GetValue(keyName).ToString();
如果您不确定值是否存在,您可以将此行更改为:
string sysRestore = rkSubKey.GetValue(keyName) as string;
然后在尝试使用它之前测试该字符串是否为空或空。
更新
另一种可能是您正在从64位操作系统上的32位应用程序执行代码。 在这种情况下,.Net有用地将您的请求重定向到
SOFTWARE\Wow6432Node\Microsoft\...
而不是。
您可以使用RegistryView.Registry64作为第二个参数使用RegistryKey.OpenBaseKey解决此问题。