0

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.

1
  • 1
    Given that error message, there is zero chance that products is not null. So you'll need to work out whylocalMachine.OpenSubKey(productsRoot); didn't return anything. Commented Jun 22, 2020 at 21:39

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I think I would have designed OpenSubKey so that it throws a meaningful exception instead of silently returning nothing.
Sorry for the late reply I am going to read the link you gave me, and will be back to you.
@RobertHarvey agree. It should have used the "TryParse pattern", eg bool TryOpenSubKey(KeyName, out RegistryKey ) if they wanted to avoid throwing exception, but I think that pattern didn't really show up until .NET 2.0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.