博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# Window Service安装、卸载、恢复选项操作
阅读量:6345 次
发布时间:2019-06-22

本文共 4834 字,大约阅读时间需要 16 分钟。

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

    }

}

转载于:https://www.cnblogs.com/94cool/p/10724872.html

你可能感兴趣的文章
代理与反向代理
查看>>
Codeforces 432C
查看>>
学习之路
查看>>
面试题13:在O(1)时间删除链表节点
查看>>
第五十六课、函数模板的概念和意义
查看>>
Windows进程创建的流程分析
查看>>
css重直居中代码
查看>>
Struts 2 ModelDriven Action
查看>>
destoon公司搜索页面显示公司类型
查看>>
C++分享笔记:5X5单词字谜游戏设计
查看>>
单片机软件proteus的汉化步骤
查看>>
webqq协议分析之~~~~登陆
查看>>
构建之法阅读笔记6
查看>>
c# 免费版pdf转word尝试
查看>>
iOS学习笔记12-UISearchBar
查看>>
用代码实现以下程序:篮子中有10个玩具,每60秒取出3个,同时每40秒向篮子中放入1个,不断重复上述动作,当篮子中剩余玩具不足3个是,程序结束...
查看>>
使用JDBC-ODBC读取Excel文件
查看>>
(一)在HTML页面中实现一个简单的Tab
查看>>
jinian
查看>>
SQL Serever学习5——数据库配置
查看>>