C#编写windows服务与调试
2017-10-10 15:51
531 查看
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服务窗口中停止该服务,可以发现进入断点部分。
相关文章推荐
- C# 编写Windows服务在VS中调试的步骤
- c# Windows 服务程序编写与调试
- c# 编写windows 服务,并制作安装包
- 编写Windows服务(C#)
- C#编写Windows服务
- C# Windows服务的开发和部署,调试(运用Timer)
- C#编写Windows服务程序图文教程
- C#制作Windows service服务系列二:演示一个定期执行的windows服务及调试(windows service)(转载)
- C#制作Windows service服务系列二--演示一个定期执行的windows服务及调试
- C# 编写Windows Service(windows服务程序)
- C#编写Windows服务程序图文教程
- C#编写Windows服务程序
- C#编写Windows服务程序图文教程
- C#制作Windows service服务系列二:演示一个定期执行的windows服务及调试(windows service)
- C# VS 2010创建、安装、调试 windows服务(windows service)
- c#+windows环境 编写mysql集群服务
- c#创建、安装、卸载、调试windows服务的简单事例
- C#编写windows服务,多服务为什么只启动一个(ServiceBase.Run)
- 在 C# 平台中, 编写 Windows 服务的简单例子
- C#编写Windows服务的基本过程