2016-01-13 112 views
0

我下面的代码失败,不管管理员与否:读取注册表值崩溃,如果我运行它

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

我得到我不能解码此错误消息:

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

我知道这个值存在,它也包含数据。

*编辑:就像我说的那样,它不应该为空,因为数据存在。如果它是空的,那么我将需要知道为什么它是空的。因此,关于什么是System.NullReferenceException的问题完全不会帮助我。

+2

的可能的复制[什么是一个NullReferenceException,如何解决呢?(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i -fix-it) – Dmitry

+0

@Dmitry就像我说过的,它不是null。或者如果是的话我不知道为什么。所以我相信这个问题是有效的。 – fishmong3r

+0

*我知道这个值存在,它也包含数据。*您如何知道这一点?你认为它可能是一个x86键,而你的.NET应用程序在x64 CLR上运行(或相反)? –

回答

3

由于raj的回答在this SO question中指出,与您的类似,问题可能是您在64位操作系统上打开注册表。

试试这个办法,而不是(.NET 4.0或更高版本):

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

...并将其替换代码:

string keyPath = @"SOFTWARE\Microsoft\CCM\LocationServices"; 
string keyName = "DnsSuffix"; 

var value = HKLMRegistryHelper.GetRegistryValue(keyPath, keyName); 
+0

链接只有答案一般皱眉,即使它链接到另一个线程。您能否将作品中相关部分的代码放入您的文章中,并授予作者? – Equalsk

+0

感谢您的输入!我正在更新我的答案。 –

0

读取注册表以 “Registry.LocalMachine” 即可不可靠,因为它默认为当前应用程序平台目标(x86/x64),以及何时它是64位Registry.LocalMachine可以查看密钥但无法访问其中的数据。

尝试使用RegistryKey指定视图。

var stuff = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) 
       .OpenSubKey("Software\\Microsoft\\CCM\\LocationServices", true); 
var value = stuff.GetValue("DnsSuffix").ToString();