0
我想開發一種方法來讀取機器上安裝的程序。C#異常讀取註冊表:空引用異常
public void refreshProgramsFromWindows() {
string SoftwareKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products";
RegistryKey rk = default(RegistryKey);
rk = Registry.LocalMachine.OpenSubKey(SoftwareKey);
//string skname = null;
string sname = string.Empty;
// New list from scratch
this.installedSoftwareList = new List<software>();
// Object software info
software aSoftware = new software();
foreach (string skname in rk.GetSubKeyNames())
{
// Reset software info
aSoftware.reset();
try
{
// Name of the programm
sname = Registry.LocalMachine.OpenSubKey(SoftwareKey).OpenSubKey(skname).OpenSubKey("InstallProperties").GetValue("DisplayName").ToString();
aSoftware.name = sname;
// Write program to the list
installedSoftwareList.Add(aSoftware);
}
catch (Exception ex)
{
}
}
網絡框架是4.5,我在Windows 7/8。當我調試這段代碼var rk爲null時,它在foreach中引發一個空引用異常。應用程序清單設置爲需要管理員權限,所以註冊表是可讀的。問題是什麼?
非常感謝您。 乾杯。
http://stackoverflow.com/questions/1268715/registry-localmachine-opensubkey-returns-null – OldProgrammer 2013-04-22 02:19:06