码迷,mamicode.com
首页 > Windows程序 > 详细

C# 编写windows服务

时间:2018-11-16 18:49:17      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:base   strong   .exe   属性   dal   void   app   mes   count   

一、编写windows服务 

1、VS2017  - 创建服务Myservice

2、创建好项目之后 --- >> 双击 Service1.cs  ---- >>  出现一个设计界面   ---->> 右键界面  --- >> 弹出对话框选择  ”添加安装程序“

3、在设计界面修改 serviceProcessInstaller1的属性 Account 为 LocalSystem  (也可用代码修改)

4、在设计界面修改 serviceInstaller1 的属性: display 为  myfirstservice  ;    description 为 我的首个服务  ;   StartType 为 Automatic

5、修改Service1.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 Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            System.IO.File.AppendAllText(@"D:\Log.txt", " Service Start :" + DateTime.Now.ToString());
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            System.IO.File.AppendAllText(@"D:\Log.txt", " Service Stop :" + DateTime.Now.ToString());
        }
    }
}

6、生成解决方案,可以在项目的dubug目录中找到 myservice.exe

二、SC命令=====安装、开启、配置、关闭windows服务

1、将myservice.exe放在英文目录下,我的是  d:\myservice.exe

2、在cmd中,转到D:并执行以下使命令进行服务安装和启动(这里的myserv 是自定义的名字)

sc create myserv  binPath= "d:/myservice.exe"sc config  myserv start= auto                      //(自动)   (DEMAND----手动、DISABLED----禁用) 并且start连着=   ,而=的后面有一个空格

net start  myserv         

可以看到d盘下已生成了log.txt

3.删除服务,执行以下代码

  sc delete myserv

 

 

 

C# 编写windows服务

标签:base   strong   .exe   属性   dal   void   app   mes   count   

原文地址:https://www.cnblogs.com/pu369/p/9970911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!