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. git操作:WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! (警告:远程主机标识已更改!)

    问题背景: 前几日,把云服务器系统由centos改成Ubuntu之后,重新搭建的git服务器环境. 问题描述: 从本机不能clone远程git仓库. 报错如下: @@@@@@@@@@@@@@@@@@@ ...

  2. WebLogic使用总结(一)——WebLogic安装

    一.下载WebLogic 到Oracle官网http://www.oracle.com/ 下载WebLogic(根据自己的情况选择),本文档下载的是Generic WebLogic Server an ...

  3. 【转】傅盛:一家公司最大瓶颈就是CEO

    创业之路,一经踏上,即永无止境.当然,对于初创期的CEO而言,还是有一些方法论可循. 来源 | 盛盛GO(ID:fstalk) 文  | 傅盛 经常有创业者问我,如何当好创业公司CEO,或如何创业,我 ...

  4. ISP PIPLINE (四) Demosaic

    what is the Demosaic? CMOS/CCD在成像时,CFA(color filter array),CFA过滤不同频段的光,因此,Sensor的输出的RAW数据信号包含了3个通道的信 ...

  5. 2017-2018 ACM-ICPC Pacific Northwest Regional Contest (Div. 1)

    A. Odd Palindrome 所有回文子串长度都是奇数等价于不存在长度为$2$的偶回文子串,即相邻两个字符都不同. #include<cstdio> #include<cstr ...

  6. js递归遍历多维数组并在修改数组的key后返回新的多维数组

    我司最近正在用VUE做一个基于用户权限显示不同左侧菜单的后台管理系统,接口会根据用户的权限不同返回不同的菜单名称.URL等,前端要将这些菜单名称及URL动态添加到系统的左侧,这里就用到了vue-rou ...

  7. Codeforces Round #547 (Div. 3)

    我老人家走了四公里吃个汉堡还没吃成.垃圾肯德基.垃圾春分半价桶. 蜜雪冰城百香果加冰+烤串真是爽死了.原来二十多块钱可以吃的这么爽. A: #include <bits/stdc++.h> ...

  8. mysql - Truncated incorrect DOUBLE value: 'undefined'

    mysql - Truncated incorrect DOUBLE value: 'undefined' 我是怎么遇到这个问题的? 我要从多个表里,查询统计数据,保存到统计表里,需要执行下面这种结构 ...

  9. java.text.DateFormat 线程不安全问题

    java.text下的 DateFormat 是线程不安全的: 建议1: 1.使用threadLocal包装DateFormat(太复杂,不推荐) 2.使用org.apache.commons.lan ...

  10. LeetCode 242 Valid Anagram 解题报告

    题目要求 Given two strings s and t , write a function to determine if t is an anagram of s. 题目分析及思路 给出两个 ...