C#从注册表获取SystemRestore的状态

时间:2011-12-23 20:38:31

标签: c# .net windows windows-7 registry

我试图阅读注册表项" RPSessionInterval"来自子键" HKLM \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ SystemRestore"在C#中。我使用以下代码并获取异常"对象引用未设置为对象的实例。"

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;
    }
}

这是一张显示注册表项实际存在的图片:

Image

2 个答案:

答案 0 :(得分:4)

对于SystemRestoreStatus的调用,您很可能会遇到拼写问题,这会导致以下行发生异常:

string sysRestore = rkSubKey.GetValue(keyName).ToString();

如果您不确定该值是否存在,可以将此行更改为:

string sysRestore = rkSubKey.GetValue(keyName) as string;

然后在尝试使用它之前测试该字符串是否为null或空。

<强>更新

另一种可能性是您在64位操作系统上执行32位应用程序的代码。在这种情况下,.Net可以帮助您将请求重定向到

SOFTWARE\Wow6432Node\Microsoft\...
而不是

节点。

您可以使用RegistryKey.OpenBaseKey作为第二个参数,使用RegistryView.Registry64解决此问题。

答案 1 :(得分:3)

您的C#应用​​程序可能有错误的位数。 By default, a Visual Studio 2010 C# project will compile to x86 (32-bit)。在64位操作系统上运行的32位应用程序通常只能访问32位注册表the contents of which are often different than the native 64-bit registryChange the architecture to "Any CPU" or "x64"它可能有用。