C#Windows Server基础教程(创建Windows服务)

Windows服务基础教程,什么是Windows服务这里就不介绍了,需要的话自己查一查就好,下面直接上干货。

一、新建 Windows 服务项目

    

    下面是新建完的样子

    

二、添加服务安装程序

  1.添加安装程序

  

  点击完出现

  

  2.设置安装程序

    将serviceName值修改为WindowsServiceTest

    

  3.修改安装权限

    将Account值修改为LocalSystem

    

三、写入服务逻辑代码

  

   1.编写Windows服务逻辑

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;

namespace WindowsService
{
  public partial class Service1 : ServiceBase
  {
    public Service1()
    {
      InitializeComponent();
    }
    //Windows服务 开始 手动在C盘创建Interfacelog文件夹,在Interfacelog文件夹里创建test.txt
    protected override void OnStart(string[] args)
    {
      using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\Interfacelog\test.txt", true))
      {
        sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
      }
    }
    //Windows服务 结束 手动在C盘创建Interfacelog文件夹,在Interfacelog文件夹里创建test.txt
    protected override void OnStop()
    {
      using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\Interfacelog\test.txt", true))
      {
        sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
      }
    }
  }
}

 

    这是在开始和结束Windows服务时写入当前时间,生成解决方案。

四、安装脚本

    

    在项目的bin\Debug里添加两个txt文件, 安装和卸载   右键重命名修改为.bat 文件

    

     编辑 安装.bat 写入以下代码

 

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe C:\Users\hasee\Desktop\Windows服务\WindowsService\WindowsService\bin\Debug\WindowsService.exe
Net Start WindowsServiceTest
sc config WindowsServiceTest start= auto
pause

 

 

    第一行 C:\Users\hasee\Desktop\Windows服务\WindowsService\WindowsService\bin\Debug\WindowsService.exe 是WindowsService.exe所在的路径
    第二行表示启动Windows服务
    第三行表示设置自动启动
    第四行是让cmd命令框显示出来,可以看到安装是否成功

    编辑 卸载.bat 写入以下
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u C:\Users\hasee\Desktop\Windows服务\WindowsService\WindowsService\bin\Debug\WindowsService.exe
pause
    右键以管理员身份运行安装.bat(不使用管理员身份运行会提示安装不成功),下面是安装成功的界面。

    

    安装成功以后,打开test.txt里面就会有启动成功的记录,卸载的话也会有卸载记录。

    

五、调试Windows服务

  调试windows服务时请确保程序已经安装并启动。

    1.点击调试>附加到进程

    

    2.选中要调试Windows 服务

    

    如果不是以管理员身份运行的项目会出现以下情况,点击使用其他凭据重新启动

    

    再执行1,2的操作,之后选中Service1.CS 查看代码  在Windows服务  结束里加上断点

    

    之后以管理员身份运行卸载.bat,就会进入断点(或者在服务里暂停该程序也是可以的)

    

六、总结

    Windows服务比较麻烦的地方就是调试了,如果你对逻辑代码进行了修改,要重新生成解决方案,并且要把Windows服务卸载了再安装一遍才能进调试,新更改的代码才会生效。

 

posted @ 2017-06-14 13:54  飞天入地程序员  阅读(1572)  评论(0)    收藏  举报