获取已安装的Msi的产品代码

San*_*eep 6 c# windows-installer

我有一个C#程序,我必须得到已安装的msi的产品代码.我只有msi名称作为输入.这可以通过编程方式完成吗?

Vla*_*nov 7

有最快速和简单的方法 - 使用条件查询字符串的WMI.

    public string GetProductCode(string productName)
    {
        string query = string.Format("select * from Win32_Product where Name='{0}'", productName);
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
        {
            foreach (ManagementObject product in searcher.Get())
                return product["IdentifyingNumber"].ToString();
        }
        return null;
    }
Run Code Online (Sandbox Code Playgroud)


Tho*_*mar 6

这个问题的答案有帮助吗?他们想获得产品名称,但也许它适用于产品代码?

编辑
如果您没有MSI文件本身来访问数据库(如上面链接到另一个问题所示),您可以尝试在以下注册表路径中搜索MSI文件的名称:

HKEY_CLASSES_ROOT\Installer\Products\*\SourceList 
Run Code Online (Sandbox Code Playgroud)

Products分支机构下有许多条目.它们中的每一个都是产品密钥.每个分支都应包含SourceList节点,而节点又应包含该值PackageName.该值保存MSI文件的名称.

所以我要做的是:

for each key in Products
{
    open SourceList subkey
    read PackageName value
    if name equals my msi file name
    {
        return key-name formatted as GUID
    }
}
Run Code Online (Sandbox Code Playgroud)


San*_*eep 5

这是我用来获取UninstallString任何 MSI的代码。

private string GetUninstallString(string msiName)
{
    Utility.WriteLog("Entered GetUninstallString(msiName) - Parameters: msiName = " + msiName);
    string uninstallString = string.Empty;
    try
    {
        string path = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products";

        RegistryKey key = Registry.LocalMachine.OpenSubKey(path);

        foreach (string tempKeyName in key.GetSubKeyNames())
        {
            RegistryKey tempKey = key.OpenSubKey(tempKeyName + "\\InstallProperties");
            if (tempKey != null)
            {
                if (string.Equals(Convert.ToString(tempKey.GetValue("DisplayName")), msiName, StringComparison.CurrentCultureIgnoreCase))
                {
                    uninstallString = Convert.ToString(tempKey.GetValue("UninstallString"));
                    uninstallString = uninstallString.Replace("/I", "/X");
                    uninstallString = uninstallString.Replace("MsiExec.exe", "").Trim();
                    uninstallString += " /quiet /qn";
                    break;
                }
            }
        }

        return uninstallString;
    }
    catch (Exception ex)
    {
        throw new ApplicationException(ex.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将给出如下结果:

MsiExec.exe /I{6BB09011-69E1-472F-ACAD-FA0E7DA3E2CE}
Run Code Online (Sandbox Code Playgroud)

从此字符串中,您可以获取大括号 {} 内的子字符串,即6BB09011-69E1-472F-ACAD-FA0E7DA3E2CE. 我希望这可能是产品代码。

  • 如果您在 64 位机器上使用此代码并且您的应用程序是 32 位,这将失败,因为它会将您重定向到软件中的“Wow6432Node”。改用`RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(path)`。 (6认同)