2016-01-13 71 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();