c# msiexec.exe卸载软件,cmd命令REG DELETE 清除注册表实例

cmd执行关键代码

卸载软件:msiexec.exe /x {xxxxx-xxxx-xxxx-xxxxx} /quiet /norestart

解释:

{xxxxx-xxxx-xxxx-xxxxx}   软件productcode

/quiet  安静模式,无用户交互

/norestart  安装完成后不重新启动

 

清理注册表:REG DELETE "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\xxxxxxx" /f

解释:

 /f  不用提示就强行删除

cmd命令查看帮助

 

 

界面

CmdHelper.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text; 

namespace UninstallTest
{
    public class CmdHelper
    {
        private static string CmdPath = @"C:\Windows\System32\cmd.exe";

        /// <summary>
        /// 执行cmd命令
        /// 多命令请使用批处理命令连接符:
        /// <![CDATA[
        /// &:同时执行两个命令
        /// |:将上一个命令的输出,作为下一个命令的输入
        /// &&:当&&前的命令成功时,才执行&&后的命令
        /// ||:当||前的命令失败时,才执行||后的命令]]>
        /// 其他请百度
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="output"></param>
        public static void RunCmd(string cmd, out string output)
        {
            cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
            using (Process p = new Process())
            {
                p.StartInfo.FileName = CmdPath;
                p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;          //不显示程序窗口
                p.Start();//启动程序

                //向cmd窗口写入命令
                p.StandardInput.WriteLine(cmd);
                p.StandardInput.AutoFlush = true;

                //获取cmd窗口的输出信息
                output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();//等待程序执行完退出进程
                p.Close();
            }
        }
    }
}

Form1.cs

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text; 
using System.Windows.Forms;

namespace UninstallTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
        }

        #region 事件
        void Form1_Load(object sender, EventArgs e)
        {
            this.textBox1.Text = "upos";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.richTextBox1.Text = "";
            this.richTextBox2.Text = "";
            var msg = "";
            try
            {
                var input = this.textBox1.Text;
                if (string.IsNullOrEmpty(input))
                {
                    throw new Exception("请输入productcode");
                }
                var urls = new List<string>();
                var result = GetAllProductCode(input, urls);
                msg = string.Join("\r\n", result.ToArray());
                if (string.IsNullOrEmpty(msg))
                {
                    throw new Exception("未找到productCode");
                }
                this.richTextBox2.Text = string.Join("\r\n", urls.ToArray());
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            this.richTextBox1.Text = msg;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var msg = "";
            try
            {
                //卸载
                var productcodes = this.richTextBox1.Text;
                var productcodelst = productcodes.Split(new string[] { "\r", "\n", "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in productcodelst)
                {
                    using (Process p = new Process())
                    {
                        p.StartInfo.FileName = "msiexec.exe";
                        p.StartInfo.Arguments = "/x {" + item + "} /quiet /norestart";
                        p.Start();
                        p.WaitForExit();
                    }
                }
                //清理注册表
                var urls = this.richTextBox2.Text;
                var urllst = urls.Split(new string[] { "\r", "\n", "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in urllst)
                {
                    var result = "";
                    var cmd = "REG DELETE \"" + item + "\" /f";
                    CmdHelper.RunCmd(cmd, out result);
                }

                msg = "已完成";
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            this.richTextBox1.Text = msg;
        } 

        private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A)
            {
                (sender as RichTextBox).SelectAll();
            }
        }

        #endregion

        #region 方法

        public static List<string> GetAllProductCode(string displayName, List<string> urls)
        {
            var result = new List<string>();
            urls.Clear();

            // 如果是32位操作系统,(或者系统是64位,程序也是64位)
            string bit32 = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            // 如果操作系统是64位并且程序是32位的
            string bit64 = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";

            RegistryKey localMachine = Registry.LocalMachine;
            //1
            RegistryKey Uninstall32 = localMachine.OpenSubKey(bit32, true);
            foreach (string subkey in Uninstall32.GetSubKeyNames())
            {
                RegistryKey productcode = Uninstall32.OpenSubKey(subkey);
                try
                {
                    string displayname = productcode.GetValue("DisplayName").ToString();
                    if (displayname.ToLower().Contains(displayName.ToLower()))
                    {
                        urls.Add(productcode.ToString());
                        string productCode = string.Empty;
                        string uninstallString = productcode.GetValue("UninstallString").ToString();

                        string[] strs = uninstallString.Split(new char[2] { '{', '}' });
                        productCode = strs[1];

                        result.Add(productCode);
                    }
                }
                catch { }
            }
            //2
            RegistryKey Uninstall64 = localMachine.OpenSubKey(bit64, true);
            foreach (string subkey in Uninstall64.GetSubKeyNames())
            {
                RegistryKey productcode = Uninstall64.OpenSubKey(subkey);
                try
                {
                    string displayname = productcode.GetValue("DisplayName").ToString();
                    if (displayname.ToLower().Contains(displayName.ToLower()))
                    {
                        urls.Add(productcode.ToString());
                        string productCode = string.Empty;
                        string uninstallString = productcode.GetValue("UninstallString").ToString();

                        string[] strs = uninstallString.Split(new char[2] { '{', '}' });
                        productCode = strs[1];

                        result.Add(productCode);
                    }
                }
                catch { }
            }

            return result;
        }

        #endregion
    }
}

Form1.Designer.cs

namespace UninstallTest
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.button2 = new System.Windows.Forms.Button();
            this.richTextBox2 = new System.Windows.Forms.RichTextBox();
            this.label4 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(578, 45);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(88, 39);
            this.button1.TabIndex = 0;
            this.button1.Text = "查询productCode";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(102, 45);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(229, 21);
            this.textBox1.TabIndex = 1;
            // 
            // richTextBox1
            // 
            this.richTextBox1.Location = new System.Drawing.Point(102, 89);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.ForcedVertical;
            this.richTextBox1.Size = new System.Drawing.Size(438, 120);
            this.richTextBox1.TabIndex = 2;
            this.richTextBox1.Text = "";
            this.richTextBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.richTextBox1_KeyDown);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(23, 45);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 3;
            this.label1.Text = "程序名称:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(23, 123);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(41, 12);
            this.label2.TabIndex = 4;
            this.label2.Text = "结果:";
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(578, 107);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(88, 43);
            this.button2.TabIndex = 5;
            this.button2.Text = "卸载软件";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // richTextBox2
            // 
            this.richTextBox2.Location = new System.Drawing.Point(102, 230);
            this.richTextBox2.Name = "richTextBox2";
            this.richTextBox2.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.ForcedVertical;
            this.richTextBox2.Size = new System.Drawing.Size(438, 120);
            this.richTextBox2.TabIndex = 2;
            this.richTextBox2.Text = "";
            this.richTextBox2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.richTextBox1_KeyDown);
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(23, 233);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(35, 12);
            this.label4.TabIndex = 4;
            this.label4.Text = "url:";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(733, 413);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.richTextBox2);
            this.Controls.Add(this.richTextBox1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "卸载软件/清理注册表";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.RichTextBox richTextBox2;
        private System.Windows.Forms.Label label4;
    }
}

 

posted @ 2018-06-22 09:13  735882640  阅读(3422)  评论(0编辑  收藏  举报