工程创建好之后,默认会有一个Services1.cs文件,删掉此文件,重新添加一个新Item
右击新添加的这个文件,选择View code,可以看到,有两个函数 OnStart和OnStop,OnStart函数在启动服务时执行,OnStop函数在停止服务时执行。
这两个函数的代码如下:
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.
编写批处理文件:
安装服务批处理:
卸载服务批处理:
服务安装好之后:
新闻热点
疑难解答