如何使用 C# 卸载程序?

How to uninstall a program using C#?

我正在尝试通过 Visual Studio 和可能的 CMD 使用 C# 卸载程序。我做了几次尝试,但什么也做不了。

尝试 #1:

        RegistryKey localMachine = Registry.LocalMachine;
        string productsRoot = @"C:\Program Files(x86)\Microsoft\XML";
        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("XML")))
                {
                    string uninstallCommand = (string)installProperties.GetValue("UninstallString");
                    return uninstallCommand;
                }
            }
        }

基于:https://sites.google.com/site/msdevnote/home/programmatically-uninstall-programs-with-c

尝试 #2:

Process p = new Process();
    ProcessStartInfo info = new ProcessStartInfo();
    info.FileName = "cmd.exe";
    info.RedirectStandardInput = true;
    info.UseShellExecute = false;

    p.StartInfo = info;
    p.Start();

    using (StreamWriter sw = p.StandardInput)
    {
        if (sw.BaseStream.CanWrite)
        {
            sw.WriteLine("wmic");
            sw.WriteLine("product get name");
            sw.WriteLine("XML" call uninstall);
        }
    }

基于:http://www.sevenforums.com/tutorials/272460-programs-uninstall-using-command-prompt-windows.html and Execute multiple command lines with the same process using .NET

我使用的是 Visual Studio 2012。代码目前来自主要方法 运行。感谢您的帮助。

您问的是 Windows 安装程序标签,所以如果我们谈论的是从 MSI 文件安装的产品:

尝试 1 不正确,因为 Windows 安装程序不使用 uninstallstring 卸载产品(更改它并查看它是否有所不同),并且有更好的方法。

2 使用 WMI,你可以让它工作,但同样没有必要。

我假设您知道要卸载的产品的产品代码,如果您不知道,稍后再详细介绍。因此,卸载产品 MsiConfigureProduct() 的正常 API 非常好,此处有相关示例:

How to uninstall MSI using its Product Code in c#

以及使用 msiexec.exe 和 ProductCode 的方法。

如果你需要枚举所有已安装的产品来扫描一个名字什么的,那么看这个:

How to get a list of installed software products?