• C#创建windows服务


    一、创建一个Windows Service

    1.新建项目 Windows服务

     

    2.服务命名,进入编辑

    贴代码

     1 using System;
     2 using System.Collections.Generic;
     3 using System.ComponentModel;
     4 using System.Data;
     5 using System.Diagnostics;
     6 using System.IO;
     7 using System.Linq;
     8 using System.ServiceProcess;
     9 using System.Text;
    10 using System.Threading.Tasks;
    11 
    12 namespace AirLogService
    13 {
    14     public partial class AirLogService : ServiceBase
    15     {
    16         /// <summary>
    17         /// Init
    18         /// </summary>
    19         public AirLogService()
    20         {
    21             InitializeComponent();
    22         }
    23 
    24         /// <summary>
    25         /// 操作日志
    26         /// </summary>
    27         string filePath = @"D:AirLogServiceLog.txt";
    28 
    29         /// <summary>
    30         /// 启动
    31         /// </summary>
    32         /// <param name="args"></param>
    33         protected override void OnStart(string[] args)
    34         {
    35             using (FileStream stream = new FileStream(filePath, FileMode.Append))
    36             using (StreamWriter writer = new StreamWriter(stream))
    37             {
    38                 writer.WriteLine($"{DateTime.Now},服务启动!");
    39             }
    40             this.Do();
    41         }
    42 
    43         /// <summary>
    44         /// 停止
    45         /// </summary>
    46         protected override void OnStop()
    47         {
    48             using (FileStream stream = new FileStream(filePath, FileMode.Append))
    49             using (StreamWriter writer = new StreamWriter(stream))
    50             {
    51                 writer.WriteLine($"{DateTime.Now},服务停止!");
    52             }
    53         }
    54 
    55         private void Do()
    56         {
    57         }
    58     }
    59 }

    3.双击项目“MyWindowsService”进入“MyService”设计界面,在空白位置右击鼠标弹出上下文菜单,选中“添加安装程序”

     

    4.点击“serviceInstaller1”,修改属性

    这里的“ServiceName”将来会做为服务的唯一名称

    5.点击“serviceProcessInstaller1”,在“属性”窗体将Account改为LocalSystem(服务属性系统级别)

    二、创建安装、启动、停止、卸载服务的Windows窗体

    1.新建一个Windows Form项目

    2.在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务及卸载服务

     

    3.添加引用“System.ServiceProcess”及“System.Configuration.Install”

    4.贴代码,窗体控制程序的代码

      1 using System;
      2 using System.Collections;
      3 using System.Windows.Forms;
      4 using System.ServiceProcess;
      5 using System.Configuration.Install;
      6 
      7 namespace AirServiceForm
      8 {
      9     public partial class AirServiceForm : Form
     10     {
     11         /// <summary>
     12         /// 关联服务文件
     13         /// </summary>
     14         string serviceFilePath = $"{Application.StartupPath}\AirLogService.exe";
     15         /// <summary>
     16         /// 服务名
     17         /// </summary>
     18         string serviceName = "AirLogService";
     19 
     20         /// <summary>
     21         /// Init
     22         /// </summary>
     23         public AirServiceForm()
     24         {
     25             InitializeComponent();
     26 
     27             if (this.IsServiceExisted(serviceName))
     28             {
     29                 this.btnInstall.Enabled = false;
     30                 this.btnUnInstall.Enabled = true;
     31                 if (this.IsServiceStarted(serviceName))
     32                 {
     33                     this.btnStart.Enabled = false;
     34                     this.btnStop.Enabled = true;
     35                 }
     36                 else
     37                 {
     38                     this.btnStart.Enabled = true;
     39                     this.btnStop.Enabled = false;
     40                 }
     41             }
     42             else
     43             {
     44                 this.btnInstall.Enabled = true;
     45                 this.btnUnInstall.Enabled = false;
     46                 this.btnStart.Enabled = false;
     47                 this.btnStop.Enabled = false;
     48             }
     49         }
     50 
     51         /// <summary>
     52         /// 安装 按钮
     53         /// </summary>
     54         /// <param name="sender"></param>
     55         /// <param name="e"></param>
     56         private void btnInstall_Click(object sender, EventArgs e)
     57         {
     58             if (!this.IsServiceExisted(serviceName))
     59             {
     60                 this.btnInstall.Enabled = false;
     61                 this.btnUnInstall.Enabled = true;
     62                 this.btnStart.Enabled = true;
     63                 this.InstallService(serviceFilePath);
     64             }
     65         }
     66 
     67         /// <summary>
     68         /// 启动 按钮
     69         /// </summary>
     70         /// <param name="sender"></param>
     71         /// <param name="e"></param>
     72         private void btnStart_Click(object sender, EventArgs e)
     73         {
     74             if (this.IsServiceExisted(serviceName))
     75             {
     76                 this.btnStart.Enabled = false;
     77                 this.btnStop.Enabled = true;
     78                 this.ServiceStart(serviceName);
     79             }
     80         }
     81 
     82         /// <summary>
     83         /// 暂停 按钮
     84         /// </summary>
     85         /// <param name="sender"></param>
     86         /// <param name="e"></param>
     87         private void btnStop_Click(object sender, EventArgs e)
     88         {
     89             if (this.IsServiceExisted(serviceName))
     90             {
     91                 this.btnStart.Enabled = true;
     92                 this.btnStop.Enabled = false;
     93                 this.ServiceStop(serviceName);
     94             }
     95         }
     96 
     97         /// <summary>
     98         /// 卸载 按钮
     99         /// </summary>
    100         /// <param name="sender"></param>
    101         /// <param name="e"></param>
    102         private void btnUnInstall_Click(object sender, EventArgs e)
    103         {
    104             if (this.IsServiceExisted(serviceName))
    105             {
    106                 this.btnInstall.Enabled = true;
    107                 this.btnUnInstall.Enabled = false;
    108                 this.btnStart.Enabled = false;
    109                 this.btnStop.Enabled = false;
    110                 this.ServiceStop(serviceName);
    111                 this.UninstallService(serviceFilePath);
    112             }
    113         }
    114 
    115         /// <summary>
    116         /// 判断服务是否存在
    117         /// </summary>
    118         /// <param name="serviceName"></param>
    119         /// <returns></returns>
    120         private bool IsServiceExisted(string serviceName)
    121         {
    122             ServiceController[] services = ServiceController.GetServices();
    123             foreach (ServiceController sc in services)
    124             {
    125                 if (sc.ServiceName.ToLower() == serviceName.ToLower())
    126                 {
    127                     return true;
    128                 }
    129             }
    130             return false;
    131         }
    132 
    133         /// <summary>
    134         /// 判断服务是否启动
    135         /// </summary>
    136         /// <param name="serviceName"></param>
    137         /// <returns></returns>
    138         private bool IsServiceStarted(string serviceName)
    139         {
    140             using (ServiceController control = new ServiceController(serviceName))
    141             {
    142                 if (control.Status == ServiceControllerStatus.Running)
    143                 {
    144                     return true;
    145                 }
    146             }
    147             return false;
    148         }
    149 
    150         /// <summary>
    151         /// 安装服务
    152         /// </summary>
    153         /// <param name="serviceFilePath"></param>
    154         private void InstallService(string serviceFilePath)
    155         {
    156             using (AssemblyInstaller installer = new AssemblyInstaller())
    157             {
    158                 installer.UseNewContext = true;
    159                 installer.Path = serviceFilePath;
    160                 IDictionary savedState = new Hashtable();
    161                 installer.Install(savedState);
    162                 installer.Commit(savedState);
    163             }
    164         }
    165 
    166         /// <summary>
    167         /// 卸载服务
    168         /// </summary>
    169         /// <param name="serviceFilePath"></param>
    170         private void UninstallService(string serviceFilePath)
    171         {
    172             using (AssemblyInstaller installer = new AssemblyInstaller())
    173             {
    174                 installer.UseNewContext = true;
    175                 installer.Path = serviceFilePath;
    176                 installer.Uninstall(null);
    177             }
    178         }
    179 
    180         /// <summary>
    181         /// 启动服务
    182         /// </summary>
    183         /// <param name="serviceName"></param>
    184         private void ServiceStart(string serviceName)
    185         {
    186             using (ServiceController control = new ServiceController(serviceName))
    187             {
    188                 if (control.Status == ServiceControllerStatus.Stopped)
    189                 {
    190                     control.Start();
    191                 }
    192             }
    193         }
    194 
    195         /// <summary>
    196         /// 停止服务
    197         /// </summary>
    198         /// <param name="serviceName"></param>
    199         private void ServiceStop(string serviceName)
    200         {
    201             using (ServiceController control = new ServiceController(serviceName))
    202             {
    203                 if (control.Status == ServiceControllerStatus.Running)
    204                 {
    205                     control.Stop();
    206                 }
    207             }
    208         }
    209     }
    210 }

    5.将已生成的MyWindowsService.exe引用到本Windows窗体

    6.由于需要安装服务,故需要使用UAC中Administrator的权限

    7.将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />

    8.IDE启动后,将会弹出如下所示的窗体(有的系统因UAC配置有可能不显示),需要用管理员权限打开

     三、调试

    1.界面操作服务,同时打开服务列表进行监控(services.msc)

    2.点击安装之后,就会有服务了

    四、运行调试

    同调试iis进程w3wp类似,直接附加到进程即可

  • 相关阅读:
    在o(N log N)时间内使用恒定的空间复杂度对链表进行排序
    归并排序
    The method of type must override a superclass method解决方式
    android sdk design Iconography
    android sdk design Typography
    android sdk design Metrics and Grids
    android模拟器被点击时总是自动输入C的解决
    “System.Data.Entity.ModelConfiguration.ModelValidationException”类型的未经处理的异常在 EntityFramework.dll 中发生
    js中的this使用
    MVC身份认证 解决办法 测试可行
  • 原文地址:https://www.cnblogs.com/lqyy/p/9666434.html
Copyright © 2020-2023  润新知