用命令 安装/卸载 windows服务(转)

第一种方法:

    1. 开始 ->运行 ->cmd

    2. cd到C:WINDOWSMicrosoft.NETFrameworkv2.0.50727(Framework版本号按IIS配置)

    3. 安装服务: 运行命令行 InstallUtil.exe E:/test.exe

    卸载服务: 运行命令行 InstallUtil.exe -u E:/test.exe

    这样就能删除了,但如果还是不能删除的话,没关系下面还有一种方法。

    第二种方法:

    运行-->cmd-->到c:windowssystem32文件夹下-->输入sc delete <服务名称>,然后就可以把服务卸载了

    这时候,我们可以用另外一个命令来卸载,如下:

    C:WINDOWSsystem32>sc delete MyService

    其中的 MyService 是你的服务的名字,比如如下的服务截图,它的卸载命令就可以如下写:

    sc delete "服务名"

    当然你也可以用这个工具create,start,stop服务。比如,我们就可以用下面的命令,安装服务,并把服务启动起来。

    installutil HongjunGuo.JobsWindowsService.exe

    sc start "服务名"

C# 卸载windows服务

 //卸载服务
        private void btnUninstall_Click(object sender, EventArgs e)
        {
            string path = GetWindowsServiceInstallPath("KylintechService");
            string p_Path = path + "\Kylintech_Service.exe";
            string p_ServiceName = "KylintechService";
            UnInstallService(p_Path, p_ServiceName);
            this.lblStart.Text = "状态:服务已卸载";
        }

        //二、卸载windows服务:
        private void UnInstallService(string filepath, string p_ServiceName)
        {
            try
            {
                if (ServiceIsExisted(p_ServiceName))
                {
                    //UnInstall Service
                    AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
                    myAssemblyInstaller.UseNewContext = true;
                    myAssemblyInstaller.Path = filepath;
                    myAssemblyInstaller.Uninstall(null);
                    myAssemblyInstaller.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("unInstallServiceError " + ex.Message);
            }
        }

        //三、判断window服务是否存在:
        private bool ServiceIsExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    return true;
                }
            }
            return false;
        }

原文地址:https://www.cnblogs.com/zqn518/p/3177254.html