C# Window Service安装、卸载、恢复选项操作

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 {serviceName} reset=0 actions=restart/20000/restart/20000/restart/60000 &exit";//第一、二次失败20秒后重启服务
,后续失败60秒后重启服务

                    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


    }

}

posted @ 2019-04-17 17:19  94cool  阅读(602)  评论(0编辑  收藏  举报