C# 获取卸载程序路径及进行卸载

using System;
using System.Windows.Forms;
using System.IO;
using System.Collections;

using Microsoft.Win32;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Diagnostics;

namespace hhhh
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            UnService();
        }
        private void UnService()
        {
            listBox1.Items.Clear();
            string temp = null, tempType = null;
            object displayName = null, uninstallString = null, releaseType = null;
            RegistryKey currentKey = null;
            int softNum = 0;
            RegistryKey pregkey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall");//获取指定路径下的键
            try
            {
                foreach (string item in pregkey.GetSubKeyNames())               //循环所有子键
                {
                    currentKey = pregkey.OpenSubKey(item);
                    displayName = currentKey.GetValue("DisplayName");           //获取显示名称
                    uninstallString = currentKey.GetValue("UninstallString");   //获取卸载字符串路径
                    releaseType = currentKey.GetValue("ReleaseType");           //发行类型,值是Security Update为安全更新,Update为更新
                    bool isSecurityUpdate = false;
                    if (releaseType != null)
                    {
                        tempType = releaseType.ToString();
                        if (tempType == "Security Update" || tempType == "Update")
                            isSecurityUpdate = true;
                    }
                    if (!isSecurityUpdate && displayName != null && uninstallString != null)
                    {
                        softNum++;
                        temp = displayName.ToString() + Environment.NewLine;
                        SoftUninstallItem Uninitem = new SoftUninstallItem();
                        Uninitem.SoftName = temp.Trim();
                        string paraName;
                        Uninitem.UninstallPath = getPath(uninstallString.ToString().Trim(), out paraName);
                        Uninitem.UnitstallPara = paraName;
                        listBox1.Items.Add(Uninitem);
                        //listBox1.Items.Add(Environment.NewLine + temp + "   文件路径:" + uninstallString.ToString());
                        //textBox1.Text = Environment.NewLine + uninstallString.ToString();
                    }
                }
            }
            catch (Exception E)
            {
                MessageBox.Show(E.Message.ToString());
            }
            label1.Text = "共有软件" + softNum.ToString() + "个";


            //listBox1.Items.Add("共有软件" + softNum.ToString() + "个");
            //textBox1.Text = "共有软件" + softNum.ToString() + "个" + Environment.NewLine + temp;
            pregkey.Close();
        }
        /// <summary>
        /// 获取卸载路径和卸载参数
        /// </summary>
        /// <param name="uninstallString"></param>
        /// <param name="ParaName"></param>
        /// <returns></returns>
        private string getPath(string uninstallString, out string ParaName)
        {
            ParaName = "";
            int space = uninstallString.IndexOf("."); //获取路径中.exe中的.
            if (space < 1) return uninstallString.Trim(' ', '"');
            space = uninstallString.IndexOf(" ", space);//获取路径中.exe 后的第一个空格
            if (space < 1) return uninstallString;
            ParaName = uninstallString.Substring(space + 1).Trim(' ', '"'); //空格后面就是参数
            return uninstallString.Substring(0, space).Trim(' ', '"'); //空格前面是卸载程序路径
        }



        /// <summary>
        /// 卸载服务
        /// </summary>
        /// <param name="p_Path">指定服务文件路径</param>           
        /// <returns>卸载信息 正确卸载返回""</returns>
        public static string UnInsertService(string Q_Path)
        {
            if (!File.Exists(Q_Path)) return "文件不存在!";
            FileInfo _InsertFile = new FileInfo(Q_Path);
            IDictionary _SavedState = new Hashtable();
            try
            {
                AssemblyInstaller _AssemblyInstaller = new AssemblyInstaller(Q_Path, new string[] { "/LogFile=" + _InsertFile.DirectoryName + "//" + _InsertFile.Name.Substring(0, _InsertFile.Name.Length - _InsertFile.Extension.Length) + ".log" });
                _AssemblyInstaller.UseNewContext = true;
                _AssemblyInstaller.Uninstall(_SavedState);
                _AssemblyInstaller.Commit(_SavedState);
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary> 
        /// 检查服务是否存在 
        /// </summary>
        /// <param name="serviceName"> 服务名</param>
        /// <returns></returns>
        private bool ServiceIsExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    return true;
                }
            } return false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var item = listBox1.SelectedItem as SoftUninstallItem;
            if (item == null) return;
            Process p = new Process();
            p.StartInfo.FileName = item.UninstallPath;
            p.StartInfo.Arguments = item.UnitstallPara;
            p.Start();


        }
        /// <summary>
        /// 软件卸载信息实体
        /// </summary>
        public class SoftUninstallItem
        {
            /// <summary>
            /// 软件名称
            /// </summary>
            public string SoftName { get; set; }
            /// <summary>
            /// 软件路径
            /// </summary>
            public string UninstallPath { get; set; }
            /// <summary>
            /// 参数
            /// </summary>
            public string UnitstallPara { get; set; }

            public override string ToString()
            {
                return string.Format("软件名称:{0}     卸载路径:{1} {2}", SoftName, UninstallPath, UnitstallPara);
            }
        }

    }
}

posted @ 2011-08-01 19:27  梦想(胡大利)  阅读(827)  评论(1编辑  收藏  举报