C# Windows Service (转)

本文描述了一个用C#实现的简单的Windows Service。
功能是在启动和停止服务的时候,在Windows事件查看器(Event Log)里添加一条log。

在Visual Studio 2008中建立Windows Service项目之后,会自动生成一个Service1的服务,它的名字默认是Service1,我先把它的文件名从Service1.cs改成ITSTestService.cs,然后需要在ITSTestService.cs的设计器视图的属性里,把Service Name改成ITSTestService,不然添加完服务后,启动服务时会报出这样的错误:

由于下列错误,ITS Test Service 服务启动失败:
配置成在该可执行程序中运行的这个服务不能执行该服务。

 

安装服务

sc create ITSTestService binpath= "PATH TO SERVICE EXE" type= share start= auto displayname= "ITS Test Service"

卸载服务

sc delete ITSTestService 

因为服务安装的名字是Service1。

ContractedBlock.gif ExpandedBlockStart.gif Code
 1using System;   
 2using System.Collections.Generic;   
 3using System.ComponentModel;   
 4using System.Data;   
 5using System.Diagnostics;   
 6using System.ServiceProcess;   
 7using System.Text;   
 8  
 9namespace WindowsServiceHowto   
10ExpandedBlockStart.gifContractedBlock.gif{   
11    public partial class ITSTestService : ServiceBase   
12ExpandedSubBlockStart.gifContractedSubBlock.gif    {   
13        public ITSTestService()   
14ExpandedSubBlockStart.gifContractedSubBlock.gif        {   
15            InitializeComponent();   
16        }
   
17  
18        protected override void OnStart(string[] args)   
19ExpandedSubBlockStart.gifContractedSubBlock.gif        {   
20            WriteLog("ITSTestService Started.");   
21        }
   
22  
23        protected override void OnStop()   
24ExpandedSubBlockStart.gifContractedSubBlock.gif        {   
25            WriteLog("ITSTestService Stopped.");   
26        }
   
27  
28        private void WriteLog(string eventString)   
29ExpandedSubBlockStart.gifContractedSubBlock.gif        {   
30            string source;   
31            string log;   
32            source = "ITS Test Windows Service";   
33            log = "Application";   
34  
35            if (!EventLog.SourceExists(source))   
36ExpandedSubBlockStart.gifContractedSubBlock.gif            {   
37                EventLog.CreateEventSource(source, log);   
38            }
   
39  
40            EventLog.WriteEntry(source, eventString);   
41        }
   
42    }
   
43}
  

 

源代码 :下载

转载于:https://www.cnblogs.com/Impulse/archive/2008/09/10/1288358.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值