Skip to content

C# Windows Service Howto

为项目组写了几个Howto的Case。

本文描述了一个用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 服务启动失败: 配置成在该可执行程序中运行的这个服务不能执行该服务。

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

Windows系统添加服务: sc create ITSTestService binpath= "PATH TO SERVICE EXE" type= share start= auto displayname= "ITS Test Service"

Windows系统删除服务: sc delete ITSTestService

ITSTestService.cs

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.ServiceProcess; using System.Text;

namespace WindowsServiceHowto { public partial class ITSTestService : ServiceBase { public ITSTestService() { InitializeComponent(); }

    protected override void OnStart(string[] args)
    {
        WriteLog("ITSTestService Started.");
    }

    protected override void OnStop()
    {
        WriteLog("ITSTestService Stopped.");
    }

    private void WriteLog(string eventString)
    {
        string source;
        string log;
        source = "ITS Test Windows Service";
        log = "Application";

        if (!EventLog.SourceExists(source))
        {
            EventLog.CreateEventSource(source, log);
        }

        EventLog.WriteEntry(source, eventString);
    }
}

}

下载:用Visual Studio 2008打开 http://download.nocoo.us/Download/Archive/CSharpHowto/WindowsService.rar