uninstall windows in csharp

To uninstall a Windows application using C#, a registry key containing the uninstall information needs to be located and the uninstall command needs to be executed in a new process.

First, locate the registry key corresponding to the application's uninstall information.

main.cs
string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(uninstallKey))
{
    foreach (string subKey in key.GetSubKeyNames())
    {
        using (RegistryKey sub = key.OpenSubKey(subKey))
        {
            string displayName = sub.GetValue("DisplayName") as string;
            if (displayName != null && displayName.Equals("Application Name"))
            {
                string uninstallString = sub.GetValue("UninstallString") as string;
                if (uninstallString != null)
                {
                    //uninstallString contains the command to be executed to uninstall the application
                }
                break;
            }
        }
    }
}
766 chars
21 lines

Once the uninstall command is obtained, execute it in a new Process.

main.cs
string uninstallCommand = "msiexec /x {PRODUCT_CODE}";
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", "/C " + uninstallCommand)
{
    WindowStyle = ProcessWindowStyle.Hidden
};
Process process = Process.Start(startInfo);
process.WaitForExit();
258 chars
8 lines

In the uninstallCommand, replace {PRODUCT_CODE} with the actual product code obtained from the registry key.

Note: The above code snippets only uninstall applications installed using Windows Installer. For other applications, the uninstallation command may vary.

gistlibby LogSnag