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的文件,里面记录了服务的启动时间.