如何以编程方式卸载应用程序

问题描述 投票:0回答:2

我尝试了thisthis以编程方式卸载应用程序。我没有收到任何错误或异常,但该应用程序未从我的计算机上卸载。另请参阅尝试过的代码

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 "";        
}

请帮助我使用 C# 以编程方式卸载应用程序。

c# .net visual-studio-2010
2个回答
5
投票

上面的例程将返回一个字符串,假设它找到了一个可能看起来像这样的匹配:

MsiExec.exe /X{02DA0248-DB55-44A7-8DC6-DBA573AEEA94}

您需要将其作为一个进程运行:

System.Diagnostics.Process.Start(uninstallString);

注意,它可能并不总是 msiexec,它可以是程序选择指定的任何内容。如果是 msiexec,您可以将

/q
参数附加到
uninstallString
以使其以静默方式卸载(并且不会显示那些修复/删除对话框)。

更新:如果您使用的是Windows安装程序3.0或更高版本,您还可以使用

/quiet
进行静默安装/卸载。它基本上与
/qn
相同(如果您使用的是旧版本)。 来源。感谢@JRO 提出来!


0
投票

使用

UninstallString
属性不足以卸载产品。 根据 Microsoft,该属性意味着:

UninstallString 由 Windows Installer 确定和设置。

这意味着字符串可以是

Msiexec.exe /I{someProductKey}
。这不会卸载任何东西。但是,它可以帮助您获取productKey。在 prompt commandpowershell
msiexec.exe /?
中运行将显示选项。在那里您可以看到如何卸载产品。

为了获取 productKeyCode 您可以通过多种方式执行此操作,但仅作为使用正则表达式的示例:

var uninstallCommand = (string)installProperties.GetValue ("UninstallString");
var productKey       = "{" + Regex.Match (uninstallCommand, @"\{([^(*)]*)\}").Groups[1].Value + "}"; // this only get what it is inside the curly braces

// Once you get the product key, uninstall it properly.
var processInfo = new ProcessStartInfo ();
processInfo.Arguments       = $"/uninstall {productKey} /quiet";
processInfo.CreateNoWindow  = true;
processInfo.UseShellExecute = false;
processInfo.FileName        = "msiexec.exe";
var process = System.Diagnostics.Process.Start (processInfo);
© www.soinside.com 2019 - 2024. All rights reserved.