1

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

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 为空,它在 foreach 中抛出了一个空引用异常。应用清单设置为需要管理员权限,因此注册表是可读的。问题是什么?

提前谢谢你。干杯。

4

1 回答 1

4

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

现在它可以工作了。

于 2013-04-22T02:35:49.790 回答