Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

c# - How to get a list of installed software products?

How do I get a list of software products which are installed on the system. My goal is to iterate through these, and get the installation path of a few of them.

PSEUDOCODE ( combining multiple languages :) )

foreach InstalledSoftwareProduct
    if InstalledSoftwareProduct.DisplayName LIKE *Visual Studio*
        print InstalledSoftwareProduct.Path
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use MSI api functions to enumerate all installed products. Below you will find sample code which does that.

In my code I first enumerate all products, get the product name and if it contains the string "Visual Studio" I check for the InstallLocation property. However, this property is not always set. I don't know for certain whether this is not the right property to check for or whether there is another property that always contains the target directory. Maybe the information retrieved from the InstallLocation property is sufficient for you?

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

class Program
{
    [DllImport("msi.dll", CharSet = CharSet.Unicode)]
    static extern Int32 MsiGetProductInfo(string product, string property,
        [Out] StringBuilder valueBuf, ref Int32 len);

    [DllImport("msi.dll", SetLastError = true)]
    static extern int MsiEnumProducts(int iProductIndex, 
        StringBuilder lpProductBuf);

    static void Main(string[] args)
    {
        StringBuilder sbProductCode = new StringBuilder(39);
        int iIdx = 0;
        while (
            0 == MsiEnumProducts(iIdx++, sbProductCode))
        {
            Int32 productNameLen = 512;
            StringBuilder sbProductName = new StringBuilder(productNameLen);

            MsiGetProductInfo(sbProductCode.ToString(),
                "ProductName", sbProductName, ref productNameLen);

            if (sbProductName.ToString().Contains("Visual Studio"))
            {
                Int32 installDirLen = 1024;
                StringBuilder sbInstallDir = new StringBuilder(installDirLen);

                MsiGetProductInfo(sbProductCode.ToString(),
                    "InstallLocation", sbInstallDir, ref installDirLen);

                Console.WriteLine("ProductName {0}: {1}", 
                    sbProductName, sbInstallDir);
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...