I'm trying to uninstall a program using C# via Visual Studio and possibly CMD. I made several attempts but could not getting anything to go.
Attempt #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;
}
}
}
Based on : https://sites.google.com/site/msdevnote/home/programmatically-uninstall-programs-with-c
Attempt #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);
}
}
Based on: http://www.sevenforums.com/tutorials/272460-programs-uninstall-using-command-prompt-windows.html and Execute multiple command lines with the same process using .NET
I'm using Visual Studio 2012. The code is being run from the main method for now. Thanks for any help.
You've asked with a Windows Installer tag, so if we are talking about products installed from MSI files:
Attempt 1 is incorrect because Windows Installer doesn't use the uninstallstring to uninstall products (change it and see if it makes a difference), and there are better ways.
2 uses WMI, and you could make that work but again it's unnecessary.
I'm going to assume you know the ProductCode of the thing you want to uninstall, if you don't then more about that later. So there's a perfectly good normal API to uninstall a product, MsiConfigureProduct(), and there are examples of that here:
How to uninstall MSI using its Product Code in c#
as well as ways of using msiexec.exe with the ProductCode.
If you need to enumerate all the installed products to scan for a name or something, then see this:
How to get a list of installed software products?