2011-12-23 21 views
2

我试图从C#中的子项“HKLM \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion \ SystemRestore”中读取注册表项“RPSessionInterval”。我正在使用下面的代码并得到异常“对象引用未设置为对象的实例”。C#从注册表中获取SystemRestore的状态

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

+0

Are you sure keyName =“RPSessionInterval”? – 2011-12-23 20:44:32

+0

糟糕,是的,忘记在代码中添加它。刚编辑我的代码以反映这些更改。同样的错误,仍然。 – 12hys 2011-12-23 20:47:13

+0

您确定您的应用程序具有读取您尝试访问的密钥所需的权限吗? - 编辑:如果不是那么没关系,会引发一个不同的错误。 – 2011-12-23 20:49:11

回答

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"它可能工作。

+1

这是抛出异常的正确答案。 – 2011-12-23 21:21:51

+0

是的,将项目设置为“任何CPU”似乎可以修复它。我在64位操作系统上,任何使用32位Windows的人都可以使用此应用程序,还是需要重新编译单独的32位和64位版本? – 12hys 2011-12-24 00:51:06

+0

对于需要在32位和64位平台上运行“本机”的应用程序,任何CPU都是正确的选择。它确保你*不需要重新编译。它会正常工作,除非你有原生的DLL依赖关系(如果是这种情况,你必须确保你需要的是原生DLL的x86和x64版本)。 – bobbymcr 2011-12-24 00:59:14

4

你最有可能有一个拼写问题的呼叫SystemRestoreStatus,这是造成以下行除外:

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

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

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

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

更新

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

SOFTWARE\Wow6432Node\Microsoft\... 

节点。

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

+0

是的,忘了在代码中添加它。刚编辑我的代码以反映这些更改。同样的错误,仍然。 – 12hys 2011-12-23 20:47:32

+0

@ 12hys:我刚刚添加了一些额外的信息,也可能会导致您的问题的答案。 – 2011-12-23 21:04:02