C#编写windows服务与调试
开发工具: VS2013(Windows 7)
编写windows服务
- 新建项目,在
Visual C#
下面选择Windows Service
,如果没有该选项,则在搜索框里搜索即可,之后点击新建。
* 可以将Serivce1.cs
重命名为ServiceTest.cs
* 在ServiceTest.cs[design]
窗口中右键,选择Add Installer
。在打开的项目安装设计窗口中,首先选择serviceProcessInstaller1
,将Account
设置为LocalSystem
;然后选择ServiceInstaller1
,将ServiceName
修改为ServiceTest
,这也是我们之后安装时需要的名字,可以填写DisplayName,之后在windows的服务中会显示这个名字。
* 在ServiceTest.cs中的OnStart函数与OnStop函数中添加以下代码
protected override void OnStart(string[] args)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("D:\\log.txt", true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
}
}
protected override void OnStop()
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("D:\\log.txt", true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
}
}
主要内容为在服务启动和停止时写入日志信息。
服务安装与卸载脚本的编写
服务安装与卸载均需要以管理员方式运行。在项目的exe生成目录下新建
Install.bat
与Uinstall.bat
,内容如下Install.bat
@ echo off %1 %2 ver|find "5.">nul&&goto :st mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :st","","runas",1)(window.close)&goto :eof :st copy "%~0" "%windir%\system32\" %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe %~dp0WindowsServiceTest.exe Net Start ServiceTest sc config ServiceTest start= auto pause
Uinstall.bat
@ echo off %1 %2 ver|find "5.">nul&&goto :st mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :st","","runas",1)(window.close)&goto :eof :st copy "%~0" "%windir%\system32\" %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u %~dp0WindowsServiceTest.exe pause
命令行的一些解释
@ echo off %1 %2 ver|find "5.">nul&&goto :st mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :st","","runas",1)(window.close)&goto :eof :st copy "%~0" "%windir%\system32\"
上述代码表示bat文件将以管理员权限运行,之后直接双击bat运行即可
%~dp0WindowsServiceTest.exe
%~dp0
表示当前目录,如果不添加这个,管理员权限下,可能找不到exe所处路径
调试windows服务
- 首先安装并运行windows服务,然后依次点击
DEBUG->Attach to Process
,选择需要关联的应用程序,同时在关闭的调用函数中打断点,便于调试可视化
* 在windows服务窗口中停止该服务,可以发现进入断点部分。