CSharp - C# 异常读取注册表:空引用异常

  显示原文与译文双语对照的内容

我正在尝试开发一个方法来读取机器上安装的程序。


public void refreshProgramsFromWindows () {


 string SoftwareKey ="SOFTWAREMicrosoftWindowsCurrentVersionInstallerUserDataS-1-5-18Products";


 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)


 {



 }


 }



Net框架是 4.5,当调试这段代码in时,我超过了 Windows 7/8.,并且在foreach中引发空引用异常。 应用程序清单设置为需要管理员权限,因此注册表是可以读的。 哪里有问题?

谢谢你的帮助。干杯。

时间: 原作者:

64位注册表问题:

添加了( 处理 64位注册表):


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


 }



然后改变了:


rk = Registry.LocalMachine.OpenSubKey(SoftwareKey);




rk = GetRegistryKey(SoftwareKey);



现在它可以。

原作者:
...