zoukankan      html  css  js  c++  java
  • 手把手教用C#编写Windows服务 并控制服务 安装、启动、停止、卸载

    Windows服务

    Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这种服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。还可以在不同于登录用户的特定用户帐户或默认计算机帐户的安全上下文中运行服务。

    创建Windows服务应用程序 即创建 Windows窗体应用程序 项目

    然后再项目上添加新建项

    选中Windows服务文件 出现设计界面后 在界面任意位置右键  添加安装程序

    出现如下安装界面

    选中 serviceInstaller 按 F4 可更改服务属性

    Description :服务描述

    DisplayName :服务显示名称

    ServiceName :服务的真实名称

    StartType :服务的 启动 类型 【手动启动、自动启动、禁用】

    选中 serviceProcessInstaller 按 F4 设置服务的 登录 类型

    在 MyService.cs 文件中写 服务启动 和 停止 分别 执行的 代码

    最后在 Program Main() 方法中 写调用服务的 代码

    以上操作就可以成功编写一个 Windows服务 了

    继续,我们对 Windows 服务 进行安装

    仍然创建一个 Windows 窗体应用程序 对刚创建的服务 进行操作【安装 、启动 、停止 、卸载】

     

    using System;
    using System.Collections;
    using System.Configuration.Install;
    using System.ServiceProcess;
    using System.Windows.Forms;
    
    namespace WindowsServiceInstallProgram
    {
        public partial class ServicePacageInstall : Form
        {
            public ServicePacageInstall()
            {
                InitializeComponent();
            }
    
            string serviceProgramPath = Application.StartupPath + "\MyService.exe";//安装服务路径
            string serviceName = "ownService";//安装服务名称 非 服务显示 名称
    
            /// <summary>
            /// 安装服务
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnInstallService_Click(object sender, EventArgs e)
            {
                try
                {
                    if (IsExistsService(serviceName))
                    {
                        UninstallService(serviceProgramPath);
                    }
                    InstallService(serviceProgramPath);
                    MessageBox.Show(
                        string.Format("服务【{0}】安装成功!
    时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        string.Format("服务【{0}】安装失败!
    错误信息:【{1}】", serviceName, ex.Message),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
    
            }
    
            /// <summary>
            /// 启动服务
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnLaunchService_Click(object sender, EventArgs e)
            {
                try
                {
                    if (IsExistsService(serviceName))
                    {
                        LaunchService(serviceName);
                    }
                    MessageBox.Show(
                        string.Format("服务【{0}】成功启动!
    时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        string.Format("服务【{0}】启动失败!
    错误信息:【{1}】", serviceName, ex.Message),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
    
            /// <summary>
            /// 停止服务
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnStopService_Click(object sender, EventArgs e)
            {
                try
                {
                    if (IsExistsService(serviceName))
                    {
                        StopService(serviceName);
                    }
                    MessageBox.Show(
                        string.Format("服务【{0}】成功停止!
    时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        string.Format("服务【{0}】停止失败!
    错误信息:【{1}】", serviceName, ex.Message),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
    
            /// <summary>
            /// 卸载服务
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnUninstallService_Click(object sender, EventArgs e)
            {
                try
                {
                    if (IsExistsService(serviceName))
                    {
                        StopService(serviceName);
                        UninstallService(serviceProgramPath);
                        MessageBox.Show(
                            string.Format("服务【{0}】成功卸载!
    时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(
                            string.Format("服务【{0}】不存在!
    时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                            "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        string.Format("服务【{0}】卸载失败!
    错误信息:【{1}】", serviceName, ex.Message),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
    
            #region 判断服务是否存在
            private bool IsExistsService(string serviceName)
            {
                /* 另一种方法
                得到当前计算机所有服务对象
                serviceController[] serviceControllers = ServiceController.GetServices();
                通过服务名【ServiceName】(非显示服务名DisplayServiceName) 得到服务对象①
                ServiceController serviceController = serviceControllers.SingleOrDefault(s => s.ServiceName == serviceName);
                */
                foreach (ServiceController sc in ServiceController.GetServices())
                {
                    if (sc.ServiceName.ToUpper() == serviceName.ToUpper())
                    {
                        return true;
                    }
                }
                return false;
            }
            #endregion
    
            #region 安装服务
            private void InstallService(string serviceProgramPath)
            {
                using (AssemblyInstaller installer = new AssemblyInstaller())
                {
                    installer.UseNewContext = true;
                    installer.Path = serviceProgramPath;
                    IDictionary saveState = new Hashtable();
                    installer.Install(saveState);
                    installer.Commit(saveState);
                }
            }
            #endregion
    
            #region 启动服务
            private void LaunchService(string serviceName)
            {
                using (ServiceController currentService = new ServiceController(serviceName))
                {
                    if (currentService.Status == ServiceControllerStatus.Stopped)
                    {
                        currentService.Start();
                    }
                }
            }
            #endregion
    
            #region 停止服务
            private void StopService(string serviceName)
            {
                using (ServiceController service = new ServiceController(serviceName))
                {
                    if (service.Status == ServiceControllerStatus.Running)
                    {
                        service.Stop();
                    }
                }
            }
            #endregion
    
            #region 卸载服务
            private void UninstallService(string serviceProgramPath)
            {
                using (AssemblyInstaller installer = new AssemblyInstaller())
                {
                    installer.UseNewContext = true;
                    installer.Path = this.serviceProgramPath;
                    installer.Uninstall(null);
                }
            }
            #endregion
        }
    }
    

    记得用管理员身份运行起来,否则会操作 失败的

    未用管理员权限运行结果

     管理员权限运行结果 如下

    效果如下

     

  • 相关阅读:
    耗时很长的服务器端事件中让客户端得到中间过程信息的合理解决方案(续)
    复杂一点的查询
    耗时很长的服务器端事件中让客户端得到中间过程信息的合理解决方案
    PET SHOP 4.0 初学者分析(项目分解)
    TSQL学习笔记(索引贴)
    存储过程和用户自定义函数
    c#简单的音乐播放器,支持多种格式,可扩展性强
    图片的无级缩放和无级截取(js+.net)
    在线部署web项目(适用于较大型项目)
    约束
  • 原文地址:https://www.cnblogs.com/JourneyOfFlower/p/10391633.html
Copyright © 2011-2022 走看看