C#编写Windows服务程序的图文详解


本文摘自PHP中文网,作者黄舟,侵删。

本文介绍了如何用C#创建、安装、启动、监控、卸载简单的Windows Service 的内容步骤和注意事项,需要的朋友可以参考下

一、创建一个Windows Service

1)创建Windows Service项目


2)对Service重命名

将Service1重命名为你服务名称,这里我们命名为ServiceTest。

二、创建服务安装程序

1)添加安装程序

之后我们可以看到上图,自动为我们创建了ProjectInstaller.cs以及2个安装的组件。

2)修改安装服务名

右键serviceInsraller1,选择属性,将ServiceName的值改为ServiceTest。

3)修改安装权限

右键serviceProcessInsraller1,选择属性,将Account的值改为LocalSystem。

三、写入服务代码

1)打开ServiceTest代码

右键ServiceTest,选择查看代码。

2)写入Service逻辑

添加如下代码:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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 WindowsServiceTest

{

    public partial class ServiceTest : ServiceBase

    {

        public ServiceTest()

        {

            InitializeComponent();

        }

        protected override void OnStart(string[] args)

        {

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))

            {

                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("C:\\log.txt", true))

            {

                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");

            }

        }

    }

}

这里我们的逻辑很简单,启动服务的时候写个日志,关闭的时候再写个日志。

四、创建安装脚本

阅读剩余部分

相关阅读 >>

.net用repeater实现分页效果的代码详解

浅谈.net core开发日志中edge.js是什么?如何用?

.net core mvc实现一个在线房间棋牌游戏微信支付和及时通讯的简易框架

c#中匿名委托以及lambda表达式的实例详解

.net实现简易的文件增量备份程序

c#中关于foreach遍历使用的深入理解

详解.net 同步与异步 之 mutex

.net实现后台登录验证

有关c#工厂模式简单讲解

c#中ini配置文件的图文代码详解

更多相关阅读请进入《Windows》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...