C#创建Windows服务的实现方法

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

一、创建Windows 服务

1.新建一个Windows 服务,并将项目名称改为“WindowsServiceDemo”,如下图所示:

2.在解决方案资源管理器内将Service1.cs改为MyService.cs后并点击“查看代码”图标按钮进入代码编辑器界面,如下图所示:

3.在代码编辑器内如入以下代码,如下所示:

using System;
using System.ServiceProcess;
using System.IO;

namespace WindowsServiceDemo
{
  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},服务停止!");
      }
    }
  }
}

4.双击项目“WindowsServiceDemo”进入“MyService”设计界面,在空白位置右击鼠标弹出上下文菜单,选中“添加安装程序”,如下图所示:

5.此时软件会生成两个组件,分别为“serviceInstaller1”及“serviceProcessInstaller1”,如下图所示:

6.点击“serviceInstaller1”,在“属性”窗体将ServiceName改为MyService,Description改为我的服务,StartType保持为Manual,如下图所示:

7.点击“serviceProcessInstaller1”,在“属性”窗体将Account改为LocalSystem(服务属性系统级别),如下图所示:

8.鼠标右键点击项目“WindowsServiceDemo”,在弹出的上下文菜单中选择“生成”按钮,如下图所示:

9.至此,Windows服务已经创建完毕。

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

1.在同一个解决方案里新建一个Windows Form项目,并命名为WindowsServiceClient,如下图所示:

2.将该项目设置为启动项目,并在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务及卸载服务,如下图所示:

3.按下F7进入代码编辑界面,添加引用“System.ServiceProcess”及“System.Configuration.Install”,并输入如下代码:

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}\\WindowsServiceDemo.exe";
    string serviceName = "MyService";

    //事件:安装服务
    private void button1_Click(object sender, EventArgs e)
    {
      if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
      this.InstallService(serviceFilePath);
    }

    //事件:启动服务
    private void button2_Click(object sender, EventArgs e)
    {
      if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
    }

    //事件:停止服务
    private void button3_Click(object sender, EventArgs e)
    {
      if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
    }

    //事件:卸载服务
    private void button4_Click(object sender, EventArgs e)
    {
      if (this.IsServiceExisted(serviceName))
      {
        this.ServiceStop(serviceName);
        this.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.为了后续调试服务及安装卸载服务的需要,将已生成的WindowsServiceDemo.exe引用到本Windows窗体,如下图所示:

5.由于需要安装服务,故需要使用UAC中Administrator的权限,鼠标右击项目“WindowsServiceClient”,在弹出的上下文菜单中选择“添加”->“新建项”,在弹出的选择窗体中选择“应用程序清单文件”并单击确定,如下图所示:

6.打开该文件,并将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />,如下图所示:

7.IDE启动后,将会弹出如下所示的窗体(有的系统因UAC配置有可能不显示),需要用管理员权限打开:

8.重新打开后,在IDE运行WindowsServiceClient项目;

9.使用WIN+R的方式打开运行窗体,并在窗体内输入services.msc后打开服务,如下图所示:

10.运行程序"Form1"点击窗体内的“安装服务”按钮,将会在服务中出现MyService,如下图所示:

11.点击“运行服务”按钮,将启动并运行服务,如下所示:

12.点击“停止服务”按钮,将会停止运行服务,如下图所示:

13.点击“卸载服务”按钮,将会从服务中删除MyService服务。

14.以上启动及停止服务将会写入D:\MyServiceLog.txt,内容如下所示:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#通过创建Windows服务启动程序的方法详解

    本文实例讲述了C#通过创建Windows服务启动程序的方法.分享给大家供大家参考,具体如下: 1. 新建一个Windows服务应用程序 创建项目-->Visual C# 左侧的"+"-->Windows -->Windows 服务(右侧模板)-->输入名称,确定创建项目 2. 设置Windows服务的属性(Windows服务里没有窗体,所以点击左侧设计器里空白的地方即可在右侧属性栏里看到属性) 这里属性是控制服务器是否可以停止,暂停,继续等等的操作.根据需要选择

  • c#创建windows服务入门教程实例

    用c#中创建一个windows服务非常简单,与windows服务相关的类都在System.ServiceProcess命名空间下. 每个服务都需要继承自ServiceBase类,并重写相应的启动.暂停.停止等方法. windows服务的相关信息是存放与注册表中的,所以他可以在不需要用户登录的情况下自动运行,在c#中你不需要再直接向注册表中添加信息了,c#提供了服务安装类 ServiceProcessInstaller和ServiceInstaller来实现服务的安装. 首先,用vs创建一个win

  • c#创建windows服务(Windows Services)详细步骤

    Windows服务在Visual Studio 以前的版本中叫NT服务,在VS.net启用了新的名称.用Visual C# 创建Windows服务不是一件困难的事,本文就将指导你一步一步创建一个Windows服务并使用它.这个服务在启动和停止时,向一个文本文件中写入一些文字信息. 第一步:创建服务框架 要创建一个新的 Windows 服务,可以从Visual C# 工程中选取 Windows 服务(Windows Service)选项,给工程一个新文件名,然后点击 确定.你可以看到,向导向工程文

  • 使用C#创建Windows服务的实例代码

    本文介绍了使用C#创建Windows服务的实例代码,分享给大家 一.开发环境 操作系统:Windows 10 X64 开发环境:VS2015 编程语言:C# .NET版本:.NET Framework 4.0 目标平台:X86 二.创建Windows Service 1.新建一个Windows Service,并将项目名称改为"MyWindowsService",如下图所示: 2.在解决方案资源管理器内将Service1.cs改为MyService1.cs后并点击"查看代码&

  • C#创建Windows服务的实现方法

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

  • VS2013创建Windows服务与调试服务的图文方法

    1.创建Windows服务 说明: a)Description 服务描述,直接显示到Windows服务列表中的描述: b)DisplayName 服务显示名称,直接显示到Windows服务列表中的名称: c)ServiceName 服务进程名称,安装与卸载服务时的唯一标识. 单击"serviceProcessInstaller1",在其属性窗口中设置Account帐号方式,建议为LocalService(当然也可以Account属性改为 LocalSystem,这样,不论是以哪个用户登

  • .NET Core使用Topshelf方式创建Windows服务的全过程记录

    前言 Topshelf是一个.NET Standard库,它消除了在.NET Framework和.NET Core中创建Windows服务的那些麻烦. 安装 Install-Package Topshelf 代码 using System; using System.Collections.Generic; using System.Text; using Topshelf; namespace ConsoleApp2222 { public class LoggingService : Se

  • C#创建windows系统用户的方法

    本文实例讲述了C#创建windows系统用户的方法.分享给大家供大家参考.具体如下: 下面的代码可以通过c#创建一个windows的本地系统账户,参数包括用户名.密码.显示名称.描述.是否强制修改密码.密码是否过期 /// <summary> /// method to create a new local Windows user account /// </summary> /// <param name="username">Username

  • C#用Topshelf创建Windows服务的步骤分享

    一.项目创建 创建一个控制台应用程序,项目右键->管理 NuGet 程序包->Topshelft及Topshelf.Log4Net. 二.Topshelf配置 一般来说,服务都会设置每隔多长时间执行一次任务,这里使用System.Threading.Timer来做个简单的日志记录,将日志写入到Debug\Log文件夹下.     2.1.Log4Net配置 新建一个log4net.config的配置文件,在其属性的复制到输出目录项下选择始终复制. <?xml version="

  • 用.NET创建Windows服务的方法第1/2页

    译者说明:我是通过翻译来学习C#的,文中涉及到的有Visual Studio.NET有关操作,我都根据中文版的VS.NET显示信息来处理的,可以让大家不致有误解. 作者:Mark Strawmyer 我们将研究如何创建一个作为Windows服务的应用程序.内容包含什么是Windows服务,如何创建.安装和调试它们.会用到System.ServiceProcess.ServiceBase命名空间的类. 什么是Windows服务? Windows服务应用程序是一种需要长期运行的应用程序,它对于服务器

随机推荐