zoukankan      html  css  js  c++  java
  • 用C#一步步创建Window Service (转) 沧海一粟

    一、准备条件:安装好的VS2010

    二、创建window service项目,取项目名为WinService_Test

    三、在新建好的项目中,找到Service1.cs,右击-->View Code(查看源代码)。在源代码中,OnStart方法是在服务启动时执行的,可以在这里编写服务要执行的业务逻辑代码;OnStop方法是在服务停止时执行的,一般在这里编写终止服务线程或停止业务逻辑的代码等。

    四、添加服务安装程序ProjectInstaller。

    1、在Service1.cs的设计界面(可双击Service1.cs进入此界面),右击-->Add Installer(添加安装程序);

    2、完成第一步,默认项目添加了ProjectInstaller.cs程序;

    3、双击编辑文件ProjectInstaller.Designer.cs,更改下面代码:

    1)在InitializeComponent方法中,添加代码

      this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

    2)在InitializeComponent方法中,修改this.serviceInstaller1.ServiceName为服务类的名称,默认为Service1,如果项目的服务类的名称更改了,注意一定要修改这个值,如:服务类的名称更为WinServiceTest后,对应修改代码如下:

      this.serviceInstaller1.ServiceName = "WinServiceTest";    //服务类的名称

      this.serviceInstaller1.DisplayName = "WinServiceTest";    //安装后,在window服务管理里显示的名称

      this.serviceInstaller1.Description = "Window测试服务!";   //安装后,在window服务管理里显示的描述

    五、添加window service安装的批处理命令

    1)在项目添加一个文本文件,更名为install.bat,编辑文件的内容如下:

      %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe WinService_Test.exe
      Net Start Service1

    2)在项目添加一个文本文件,更名为uninstall.bat,编辑文件的内容如下:

      Net Start Service1
      %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u WinService_Test.exe

    补充说明:

    • 上面黄色字体为项目的名称,也就是生成后的文件名称;红色字体为服务的名称,也就是服务类的名称。
    • 另外,文件install.bat的属性里“Copy to Output Directory”默认为“Do not copy”,编译后,在debug的文件夹里找不到install.bat的,要更改为“Copy always”或者“Copy if newer”才能出现的。uninstall.bat也跟install.bat一样的。

     

    六、实际安装。

    1)编译成功后,在debug文件夹中,双击install.bat完成安装;

    2)安装成功后,在window的服务里,可看到此服务,如没更改服务类的名称,这里可看到服务Service1;

    3)双击uninstall.bat可卸载此服务。

    总结,通过上面六个步骤,实现window服务从创建到安装、卸载整个过程。

  • 相关阅读:
    Microsoft Dynamics CRM2011 更换Logo
    Calling LoadLibraryEx on ISAPI filter failed
    Dynamics CRM2013/2015 插件注册工具登录后无法显示assembly列表问题的解决办法二
    python字符串
    python流程控制
    python反射
    python内置函数
    python集合
    python字符编码
    测试appstore地址
  • 原文地址:https://www.cnblogs.com/taintain1984/p/2875268.html
Copyright © 2011-2022 走看看