简体   繁体   中英

C# Exception reading registry: Null reference exception

I'm trying to develop a method to read the programs installed on the machine.

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 is 4.5 and i'm over Windows 7/8. When i debug this piece of code var rk is null, and it's throwing a null reference exception in the foreach. The app manifest is set to require admin Privileges, so the registry is readable. What is the problem?

Thanks you in advance. Cheers.

64 bits registry problem:

Added (to handle 64 bit registry):

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

And changed:

rk = Registry.LocalMachine.OpenSubKey(SoftwareKey);

to

rk = GetRegistryKey(SoftwareKey);

And now it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM