博客
关于我
使用C#创建Windows服务
阅读量:114 次
发布时间:2019-02-26

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

如何创建并管理Windows服务及其安装、启动、停止及卸载

作为开发人员,在实际项目中常需要创建并管理Windows服务。以下将详细介绍如何创建一个Windows服务及其对应的安装、启动、停止及卸载功能的Windows窗体。

一、开发环境

开发环境的选择对项目的顺利进行至关重要。具体来说:

  • 操作系统:建议使用Windows 10 X64版本。
  • 开发工具:使用Visual Studio 2015进行编码。
  • 编程语言:以C#为主要编程语言。
  • 目标平台:开发目标为X86平台。

二、创建Windows服务

1. 创建服务项目

  • 打开Visual Studio,创建一个新的Windows服务项目,项目名称建议命名为"MyWindowsService"。
  • 在解决方案资源管理器中,将默认的Service1.cs更改为MyService1.cs,然后点击“查看代码”图标进入代码编辑界面。
  • 2. 编写服务代码

    在代码编辑器中输入以下代码:

    using System;
    using System.ServiceProcess;
    using System.IO;
    namespace MyWindowsService
    {
    public partial class MyService : ServiceBase
    {
    public MyService()
    {
    InitializeComponent();
    }
    string filePath = @"D:\MyServiceLog.txt";
    protected override void OnStart(string[] args)
    {
    using (FileStream stream = new FileStream(filePath, FileMode.Append))
    using (StreamWriter writer = new StreamWriter(stream))
    {
    writer.WriteLine($"{DateTime.Now}, 服务启动!");
    }
    }
    protected override void OnStop()
    {
    using (FileStream stream = new FileStream(filePath, FileMode.Append))
    using (StreamWriter writer = new StreamWriter(stream))
    {
    writer.WriteLine($"{DateTime.Now}, 服务停止!");
    }
    }
    }
    }

    3. 设置服务属性

  • 双击项目"MyWindowsService",进入服务设计界面。

  • 在空白区域右击,选择"添加安装程序"。

  • 在服务安装程序属性窗口中设置:

    • ServiceName:设置为"MyService"。
    • Description:填写简要说明,如"我的服务"。
    • StartType:保持为"Manual"。
  • 设置服务进程属性:

    • 在服务进程安装程序属性窗口中,将"Account"设置为"LocalSystem"(服务属性设置为系统级别)。
  • 4. 生成并测试服务

    点击项目"MyWindowsService"的右键菜单中的"生成"按钮,即可完成服务的创建。

    三、创建安装、启动、停止、卸载服务的Windows窗体

    1. 创建客户端项目

  • 在同一解决方案中,新建一个Windows Form项目,命名为"WindowsServiceClient"。
  • 设置该项目为启动项目。
  • 2. 添加功能按钮

    在窗体中添加四个按钮,分别用于安装、启动、停止和卸载服务,按钮名称可分别为"安装服务"、"启动服务"、"停止服务"和"卸载服务"。

    3. 编写客户端代码

    在代码编辑器中引用必要的命名空间:

    using System;
    using System.Collections;
    using System.Windows.Forms;
    using System.ServiceProcess;
    using System.Configuration.Install;

    添加以下代码:

    namespace WindowsServiceClient
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";
    string serviceName = "MyService";
    // 安装服务
    private void button1_Click(object sender, EventArgs e)
    {
    if (IsServiceExisted(serviceName))
    UninstallService(serviceFilePath);
    InstallService(serviceFilePath);
    }
    // 启动服务
    private void button2_Click(object sender, EventArgs e)
    {
    if (IsServiceExisted(serviceName))
    ServiceStart(serviceName);
    }
    // 停止服务
    private void button4_Click(object sender, EventArgs e)
    {
    if (IsServiceExisted(serviceName))
    ServiceStop(serviceName);
    }
    // 卸载服务
    private void button3_Click(object sender, EventArgs e)
    {
    if (IsServiceExisted(serviceName))
    {
    ServiceStop(serviceName);
    UninstallService(serviceFilePath);
    }
    }
    // 判断服务是否存在
    private bool IsServiceExisted(string serviceName)
    {
    ServiceController[] services = ServiceController.GetServices();
    foreach (ServiceController sc in services)
    {
    if (sc.ServiceName.ToLower() == serviceName.ToLower())
    return true;
    }
    return false;
    }
    // 安装服务
    private void InstallService(string serviceFilePath)
    {
    using (AssemblyInstaller installer = new AssemblyInstaller())
    {
    installer.UseNewContext = true;
    installer.Path = serviceFilePath;
    IDictionary savedState = new Hashtable();
    installer.Install(savedState);
    installer.Commit(savedState);
    }
    }
    // 卸载服务
    private void UninstallService(string serviceFilePath)
    {
    using (AssemblyInstaller installer = new AssemblyInstaller())
    {
    installer.UseNewContext = true;
    installer.Path = serviceFilePath;
    installer.Uninstall(null);
    }
    }
    // 启动服务
    private void ServiceStart(string serviceName)
    {
    using (ServiceController control = new ServiceController(serviceName))
    {
    if (control.Status == ServiceControllerStatus.Stopped)
    {
    control.Start();
    }
    }
    }
    // 停止服务
    private void ServiceStop(string serviceName)
    {
    using (ServiceController control = new ServiceController(serviceName))
    {
    if (control.Status == ServiceControllerStatus.Running)
    {
    control.Stop();
    }
    }
    }
    }
    }

    4. 引用服务文件

    在项目中引用生成的"MyWindowsService.exe",确保安装、启动、停止和卸载操作正常进行。

    5. 设置管理员权限

    为了确保服务安装和操作的权限,需要使用UAC管理员权限:

  • 右键点击项目"MyWindowsServiceClient",选择"添加" > "新建项"。
  • 在新建项窗口中选择"应用程序清单文件",单击确认。
  • 打开该文件,将<requestedExecutionLevel level="asInvoker" uiAccess="false" />替换为<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
  • 6. 运行测试

  • 在IDE中运行项目"MyWindowsServiceClient"。
  • 使用WIN + R打开运行窗口,输入servicess.msc,打开服务窗口。
  • 点击各按钮分别执行安装、启动、停止和卸载操作。
  • 7. 记录日志

    服务启动和停止操作会将日志记录在D:\MyServiceLog.txt文件中,便于后续调试和监控。

    四、调试服务

    为了方便调试,按如下步骤进行:

  • MyService类中设置断点,如OnStartOnStop方法中的断点。
  • 启动"WindowsServiceClient"项目,进入调试菜单,选择"附加到进程"。
  • 在进程列表中找到"MyWindowsService.exe",点击"附加"按钮。
  • 执行"停止服务"按钮,程序将在断点处停止,方便调试。
  • 通过以上步骤,可以成功创建并管理Windows服务及其相关功能。

    转载地址:http://prtk.baihongyu.com/

    你可能感兴趣的文章
    mysql中null和空字符串的区别与问题!
    查看>>