using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;

namespace ScmWrapper
{
    public class ServiceHandler
    {
        #region 安装服务

/// <summary> 
        /// 安装服务 
        /// </summary> 
        public static bool InstallService(string nameService, string serviceFileName)
        {
            bool flag = true;
            if (!IsServiceIsExisted(nameService))
            {
                try
                {
                    using (Process myPro = new Process())
                    {
                        myPro.StartInfo.FileName = "cmd.exe";
                        myPro.StartInfo.UseShellExecute = false;
                        myPro.StartInfo.RedirectStandardInput = true;
                        myPro.StartInfo.RedirectStandardOutput = true;
                        myPro.StartInfo.RedirectStandardError = true;
                        myPro.StartInfo.CreateNoWindow = true;
                        myPro.Start();
                        //如果调用程序路径中有空格时,cmd命令执行失败,可以用双引号括起来 ,在这里两个引号表示一个引号(转义)
                        string str = $"{serviceFileName} install &exit";

myPro.StandardInput.WriteLine(str);
                        myPro.StandardInput.AutoFlush = true;
                        myPro.WaitForExit();

}

}
                catch
                {
                    flag = false;
                }

//try
                //{
                //    InstallmyService(null, serviceFileName);
                //}
                //catch (Exception ex)
                //{
                //    flag = false;
                //}

}
            return flag;
        }
        #endregion

#region 卸载服务 
        /// <summary> 
        /// 卸载服务 
        /// </summary> 
        public static bool UninstallService(string nameService, string serviceFileName)
        {
            bool flag = true;
            if (IsServiceIsExisted(nameService))
            {
                if (IsServiceStart(nameService))
                {
                    StopService(nameService);
                }
                try
                {
                    using (Process myPro = new Process())
                    {
                        myPro.StartInfo.FileName = "cmd.exe";
                        myPro.StartInfo.UseShellExecute = false;
                        myPro.StartInfo.RedirectStandardInput = true;
                        myPro.StartInfo.RedirectStandardOutput = true;
                        myPro.StartInfo.RedirectStandardError = true;
                        myPro.StartInfo.CreateNoWindow = true;
                        myPro.Start();
                        //如果调用程序路径中有空格时,cmd命令执行失败,可以用双引号括起来 ,在这里两个引号表示一个引号(转义)
                        string str = $"{serviceFileName} uninstall &exit";

myPro.StandardInput.WriteLine(str);
                        myPro.StandardInput.AutoFlush = true;
                        myPro.WaitForExit();

}
                }
                catch
                {
                    flag = false;
                }
                //try
                //{
                //    UnInstallmyService(serviceFileName);
                //}
                //catch
                //{
                //    flag = false;
                //}
            }
            return flag;
        }
        #endregion

#region 检查服务存在的存在性 
        /// <summary> 
        /// 检查服务存在的存在性 
        /// </summary> 
        /// <param name=" NameService ">服务名</param> 
        /// <returns>存在返回 true,否则返回 false;</returns> 
        public static bool IsServiceIsExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            bool exist = services.Where(n => n.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase))?.Count() > 0;
            services = null;
            return exist;
        }

#endregion

#region 判断window服务是否启动 
        /// <summary> 
        /// 判断某个Windows服务是否启动 
        /// </summary> 
        /// <returns></returns> 
        public static bool IsServiceStart(string serviceName)
        {
            ServiceController psc = new ServiceController(serviceName);
            bool bStartStatus = false;
            try
            {
                if (!psc.Status.Equals(ServiceControllerStatus.Stopped))
                {
                    bStartStatus = true;
                }

return bStartStatus;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                psc.Close();
                psc.Dispose();
            }
        }
        #endregion

#region  修改服务的启动项 
       
        public static void SetRecoveryOptions(string serviceName)
        {
            try
            {
                using (Process myPro = new Process())
                {
                    myPro.StartInfo.FileName = "cmd.exe";
                    myPro.StartInfo.UseShellExecute = false;
                    myPro.StartInfo.RedirectStandardInput = true;
                    myPro.StartInfo.RedirectStandardOutput = true;
                    myPro.StartInfo.RedirectStandardError = true;
                    myPro.StartInfo.CreateNoWindow = true;
                    myPro.Start();
                    //如果调用程序路径中有空格时,cmd命令执行失败,可以用双引号括起来 ,在这里两个引号表示一个引号(转义)
                    string str = $"sc failure GeoFence reset=0 actions=restart/60000/restart/60000/restart/60000 &exit";

myPro.StandardInput.WriteLine(str);
                    myPro.StandardInput.AutoFlush = true;
                    myPro.WaitForExit();

}

}
            catch
            {
               
            }
        }

#endregion

#region 启动服务

public static bool StartService(string serviceName)
        {
            bool flag = true;
            if (IsServiceIsExisted(serviceName))
            {
                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
                if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
                {
                    service.Start();
                    for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            flag = false;
                        }
                    }
                }
                service.Close();
                service.Dispose();
            }
            return flag;
        }
        #endregion

#region 停止服务

public static bool StopService(string serviceName)
        {
            bool flag = true;
            if (IsServiceIsExisted(serviceName))
            {
                System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
                if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    service.Stop();
                    for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            flag = false;
                        }
                    }
                }
                service.Close();
                service.Dispose();
            }
            return flag;
        }
        #endregion

}

}

C# Window Service安装、卸载、恢复选项操作的更多相关文章

  1. windows service 安装/卸载

    第一种方法: 前提: Service1 中的serviceProcessInstaller1设置 Account为localSystem 1. 开始 ->运行 ->cmd(管理员身份运行) ...

  2. Window Service安装不成功

    1. 加Winsow Service 2. 加Setup Project    Add -> Project Output , 选中Primary output from Winsow Serv ...

  3. Windows Service的安装卸载 和 Service控制(转)

    Windows Service的安装卸载 和 Service控制 原文地址:http://www.cnblogs.com/Peter-Zhang/archive/2011/10/15/2212663. ...

  4. Windows Service的安装卸载 和 Service控制

    原文 Windows Service的安装卸载 和 Service控制 本文内容包括如何通过C#代码安装Windows Service(exe文件,并非打包后的安装文件).判断Service是否存在. ...

  5. C#Windows Service服务程序的安装/卸载、启动/停止 桌面客户端管理程序设计

    C#Windows Service服务程序的安装/卸载.启动/停止 桌面客户端管理程序设计 关于Windows Service程序的安装与卸载如果每次使用命令行操作,那简直要奔溃了,太麻烦而且还容易出 ...

  6. CentOS 7安装/卸载Redis,配置service服务管理

    Redis简介 Redis功能简介 Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库.缓存和消息中间件. 相比于传统的关系型数据库,Redis的存储方式是key-va ...

  7. window如何安装redis服务、卸载redis服务和启动redis服务

    window如何安装redis服务.卸载redis服务和启动redis服务 一.总结 一句话总结:github上下载,解压,命令行运行(redis-server.exe redis.windows.c ...

  8. windows服务安装卸载

    到C盘下找到对应的开发VS的installutil.exe文件,复制到程序的执行文件(*.exe)相同目录下在开始程序中找到VS命令提示工具 转到程序的执行文件(*.exe)目录下 C:\>cd ...

  9. 创建 window service 定时任务

    参考文章:http://www.cnblogs.com/jack-liang/archive/2011/05/20/2051743.html 前段时间做过一个项目,前端系统提供添加定时任务,后端系统要 ...

随机推荐

  1. windows应用程序框架及实例

    应用程序框架:同一类型应用程序的结构大致相同,并有很多相同的源代码,因此可以通过一个应用程序框架AFX(Application FrameWorks)编写同一类型应用程序的通用源代码. 主要向导: D ...

  2. Centos6.5升级openssh、OpenSSL和wget

    1.OpenSSL 1.1.查看版本 使用如下命令查看版本: openssl version 1.2.安装gcc依赖 yum -y install gcc gcc-c++ 1.3.安装配置 ./con ...

  3. 2017-10-22—LD激光二极管原理

    直接摘抄百科了: 在讲激光产生机理之前,先讲一下受激辐射.在光辐射中存在三种辐射过程, 一是处于高能态的粒子自发向低能态跃迁,称之为自发辐射; 二是处于高能态的粒子在外来光的激发下向低能态跃迁,称之为 ...

  4. python一些语法糖用法

    @修饰符 '@'符号用作函数修饰符是python2.4新增加的功能,修饰符必须出现在函数定义前一行,不允许和函数定义在同一行.也就是说@A def f(): 是非法的. 只可以在模块或类定义层内对函数 ...

  5. vue中,对象数组多层嵌套时,更新数据更新页面

    vue中的对象和数组的元素直接赋值修改时,是不能响应到view中去的 1.对象更新 this.a={title:'列表1’}; this.a.title='列表2’; <h1>{{a.ti ...

  6. numpy中的广播

    目录 广播的引出 广播的原则 数组维度不同,后缘维度的轴长相符 数组维度相同,其中有个轴为1 参考: 广播的引出  numpy两个数组的相加.相减以及相乘都是对应元素之间的操作. import num ...

  7. ECMA Script 6_字符串_扩展_字符 是4字节还是2字节?_模板字符串

    ES6 字符串扩展 ES6 加强了对 Unicode 的支持,并且扩展了字符串对象 字符 的 Unicode 表示法 允许采用 \uxxxx 形式表示一个字符, 其中 xxxx 表示字符的 Unico ...

  8. 秒杀ecshop的前台写shell 0day

    ECSHOP号称最大的开源网店系统,官方是这样介绍它的:“ECShop网店系统是一套免费开源的网上商店软件,无论在稳定性.代码优化.运行效率.负载能力.安全等级.功能可操控性和权限严密性等方面都居国内 ...

  9. iview select filterable属性使用下拉小bug

    今天做项目时候在iview 原生自带的select中设置filterable,下拉时候可进行查询,但是发现选中载打开模态框每次都绑定上一次的值,解决方案就是在关闭弹框时候将this.$refs.sto ...

  10. body里面的onload和window.onload,window.load的区别

    区别:body里面的onload是在“页面加载完成后执行的动作”window里面的onload是在“页面加载时执行的动作” window.load这个应该只是表明事件方法,但并未执行,比如click表 ...