c#异常读取注册表:空引用异常
本文关键字:异常 引用 注册表 读取 | 更新日期: 2023-09-27 18:10:26
我正在研究一种方法来读取安装在机器上的程序。
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)
{
}
}
. Net Framework是4.5,我超过Windows 7/8。当我调试这段代码var rk为null时,它在foreach中抛出一个null引用异常。应用程序清单被设置为需要管理员权限,所以注册表是可读的。有什么问题吗?
提前谢谢你。欢呼。
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);
现在可以了