Search code examples
c#registrykey

Get Uninstall Command For a Certain Program in C#


so I am working on this code that returns an uninstall command string to uninstall a certain program. I have seen this code in other questions, but no one seems to have the same problem as me. This is the code:

public static string GetUninstallCommandFor(string productDisplayName)
    {
        RegistryKey localMachine = Registry.LocalMachine;
        string productsRoot = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UserData\S-1-5-18\Products";
        RegistryKey products = localMachine.OpenSubKey(productsRoot);
        string[] productFolders = products.GetSubKeyNames();

        foreach (string p in productFolders)
        {
            RegistryKey installProperties = products.OpenSubKey(p + @"\InstallProperties");
            if (installProperties != null)
            {
                string displayName = (string)installProperties.GetValue("DisplayName");
                if ((displayName != null) && (displayName.Contains(productDisplayName)))
                {
                    string uninstallCommand = (string)installProperties.GetValue("UninstallString");
                    return uninstallCommand;
                }
            }
        }
        return "";
    }

This code returns this error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

products was null.

I don't know how products can be empty, I did check that subkey and it was full of folders, so how can I solve this problem.


Solution

  • Build for X64. In a 32bit process you're actually reading HKEY_LOCAL_MACHINE\Software\Wow6432Node through registry redirection.

    Or you can request an un-redirected view of the registry per: Avoid Registry Wow6432Node Redirection