2013-04-28 131 views
0

我寫了下面的代碼:閱讀註冊表

RegistryKey _Key = Registry.ClassesRoot.OpenSubKey("SystemFileAssociations", true); 
foreach (String s in names) 
{ 
    System.Windows.Forms.MessageBox.Show("Done.===================" + s); 
} 
_Key.Close(); 

打印的項等於.txt

然而,當我這樣做,即嘗試訪問/HKCR/SFA/.txt關鍵是這樣的:

RegistryKey rootKey = Registry.ClassesRoot.OpenSubKey("SystemFileAssociations//.txt", true); 
rootKey.Close(); 

我得到以下錯誤:

SystemNullReferenceException: Object reference not set to an instance of an object

回答

2

拋出異常,因爲rootKey爲空(OpenSubKey操作失敗的原因,而不是//\\鍵值名稱被使用)。 使用以下代碼:

using(RegistryKey rootKey = Registry.ClassesRoot.OpenSubKey("SystemFileAssociations\\.txt", true)) { 
    if(rootKey != null) { 
     // do staff 
    } 
} 
+0

rootKey實際上不是null。我可以在註冊表中看到一個.txt條目,也可以通過我發佈的其他代碼段看到 – user2053912 2013-04-28 11:11:47

+1

@ user2053912您的代碼片段中的rootkey *變量*爲空(異常證實了這一點)。請再次檢查我的密碼 - 密鑰名稱錯誤 – DmitryG 2013-04-28 11:12:57

+2

非常抱歉。感謝您的禮貌。 – user2053912 2013-04-28 11:15:22