C#编写windows服务与调试

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.batUinstall.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服务窗口中停止该服务,可以发现进入断点部分。

这里写图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

littletomatodonkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值