C#编写Windows服务及服务操作

Windows服务

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

创建Windows服务应用程序

创建Windows服务应用程序 即创建 Windows窗体应用程序。
在这里插入图片描述
选中Windows服务文件 出现设计界面后 在界面任意位置右键 添加安装程序
在这里插入图片描述
更改安装文件属性
在这里插入图片描述
在这里插入图片描述
在 MyService.cs 文件中写 服务启动 和 停止 分别 执行的 代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace MyService
{
    public partial class MyService : ServiceBase
    {
        public MyService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("D:\\info.txt", true))
            {
                sw.WriteLine("MyService");
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
            }
        }

        protected override void OnStop()
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("D:\\info.txt", true))
            {
                sw.WriteLine("MyService");
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
            }
        }
    }
}

Windows服务辅助类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Collections;
using Microsoft.Win32;

namespace WindowsFormsApp1
{
    public class WindowsServiceHelp
    {
        /// <summary>
        /// 判断服务是否存在
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public 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;
        }

        /// <summary>
        /// 安装服务
        /// </summary>
        /// <param name="serviceProgramPath"></param>
        public 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);
            }
        }

        /// <summary>
        /// 服务是否启动
        /// </summary>
        /// <returns></returns>
        private bool ServiceIsRunning(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);
            if (service.Status == ServiceControllerStatus.Running)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="serviceName"></param>
        public void LaunchService(string serviceName)
        {
            using (ServiceController currentService = new ServiceController(serviceName))
            {
                if (currentService.Status == ServiceControllerStatus.Stopped)
                {
                    currentService.Start();
                }
            }
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="serviceName"></param>
        public void StopService(string serviceName)
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                if (service.Status == ServiceControllerStatus.Running)
                {
                    service.Stop();
                }
            }
        }

        /// <summary>
        /// 卸载服务
        /// </summary>
        /// <param name="serviceProgramPath"></param>
        public void UninstallService(string serviceProgramPath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceProgramPath;
                installer.Uninstall(null);
            }
        }

        /// <summary>
        /// 设置服务启动类型
        /// 2为自动 3为手动 4 为禁用
        /// </summary>
        /// <param name="startType"></param>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public bool ChangeServiceStartType(int startType, string serviceName)
        {
            try
            {
                RegistryKey regist = Registry.LocalMachine;
                RegistryKey sysReg = regist.OpenSubKey("SYSTEM");
                RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet");
                RegistryKey services = currentControlSet.OpenSubKey("Services");
                RegistryKey servicesName = services.OpenSubKey(serviceName, true);
                servicesName.SetValue("Start", startType);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
    }
}

创建Windows 窗体应用程序

在这里插入图片描述
在这里插入图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration.Install;
using System.Collections;
using System.ServiceProcess;

namespace WindowsFormsApp1
{
    public partial class FrmServiceHelp : Form
    {
        string serviceProgramPath = Application.StartupPath + "\\MyService.exe";//安装服务路径
        string serviceName = "NickService";//安装服务名称 非 服务显示 名称
        WindowsServiceHelp serviceHelp = new WindowsServiceHelp();
        public FrmServiceHelp()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 安装服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceHelp.IsExistsService(serviceName))
                {
                    serviceHelp.UninstallService(serviceProgramPath);
                }
                serviceHelp.InstallService(serviceProgramPath);
                MessageBox.Show(
                    string.Format("服务【{0}】安装成功!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服务【{0}】安装失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceHelp.IsExistsService(serviceName))
                {
                    serviceHelp.LaunchService(serviceName);
                }
                MessageBox.Show(
                    string.Format("服务【{0}】成功启动!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服务【{0}】启动失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceHelp.IsExistsService(serviceName))
                {
                    serviceHelp.StopService(serviceName);
                }
                MessageBox.Show(
                    string.Format("服务【{0}】成功停止!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服务【{0}】停止失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        /// <summary>
        /// 卸载服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceHelp.IsExistsService(serviceName))
                {
                    serviceHelp.StopService(serviceName);
                    serviceHelp.UninstallService(serviceProgramPath);
                    MessageBox.Show(
                        string.Format("服务【{0}】成功卸载!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(
                        string.Format("服务【{0}】不存在!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服务【{0}】卸载失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
    }
}

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# Windows服务是一种在后台运行的应用程序,可以在Windows操作系统中作为服务安装和运行。Windows服务可以在系统启动时自动启动,并在后台持续运行,而不需要用户登录。它们通常用于执行一些长时间运行的任务或提供后台功能。 要创建一个C# Windows服务,你可以使用Visual Studio来创建一个新的Windows服务项目。在项目中,你可以编写代码来定义服务的行为和功能。在服务的主要代码中,你可以使用引用\[2\]中的方法来启动和停止服务。通过使用ServiceController类,你可以检查服务的状态并执行相应的操作。 例如,你可以使用引用\[3\]中的方法来判断服务是否在运行状态。这个方法会遍历系统中的所有服务,并检查每个服务的状态。如果找到了指定的服务,并且它的状态是运行中,那么就返回true,否则返回false。 在安装和卸载Windows服务时,你可以使用引用\[1\]中的命令行代码。这个命令行代码使用InstallUtil工具来安装或卸载服务。你需要提供服务的可执行文件路径和名称。 总之,C# Windows服务是一种在后台运行的应用程序,可以通过编写代码来定义其行为和功能。你可以使用ServiceController类来控制服务的启动、停止和状态检查。在安装和卸载服务时,你可以使用InstallUtil工具来执行相应的操作。 #### 引用[.reference_title] - *1* [Windows服务一:新建Windows服务、安装、卸载服务](https://blog.csdn.net/weixin_34378969/article/details/85840546)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [【C#Windows服务(Service)安装及启停](https://blog.csdn.net/youcheng_ge/article/details/124053794)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值