C#编写Windows服务实例代码
使用Microsoft Visual Studio2012可以很方便的创建一个Windows服务,本例实现一个向D盘的txt文件里,写入系统时间的Windows服务。
新建一个Windows Services工程:
工程创建好之后,默认会有一个Services1.cs文件,删掉此文件,重新添加一个新Item
右击新添加的这个文件,选择View code,可以看到,有两个函数 OnStart和OnStop,OnStart函数在启动服务时执行,OnStop函数在停止服务时执行。
这两个函数的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace MyFirstWindowsService
{
partial class MyWindowsService : ServiceBase
{
public MyWindowsService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
FileStream fileStream = new FileStream(@"D:\MyWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.BaseStream.Seek(0, SeekOrigin.End);
streamWriter.WriteLine("My service started" + DateTime.Now.ToString() + "\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
FileStream fileStream = new FileStream(@"D:\MyWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.BaseStream.Seek(0, SeekOrigin.End);
streamWriter.WriteLine("My service stopped " + DateTime.Now.ToString() + "\n");
streamWriter.Flush();
streamWriter.Close();
fileStream.Close();
}
}
}
之后需要新建一个安装组件MyWindowsServiceProjectInstaller(右击MyWindowsService.cs这个文件选择view desiner,然后选择Add Installer),需要将MyFirstWindowsServiceProcessInstaller的account属性设置为localservice.
编写批处理文件:
安装服务批处理:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe C:\Users\gaoja1\Desktop\MyWindowsService\MyFirstWindowsService\bin\Debug\MyFirstWindowsService.exe
Net Start ServiceTest
sc config ServiceTest start= auto
卸载服务批处理:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u C:\Users\gaoja1\Desktop\MyWindowsService\MyFirstWindowsService\bin\Debug\MyFirstWindowsService.exe
服务安装好之后:
服务启动之后可以在D盘看到一个txt的文件,里面记录了服务的启动时间.