Window服务介绍

Microsoft Windows 服务能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这使服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。还可以在不同于登录用户的特定用户帐户或默认计算机帐户的安全上下文中运行服务。本文就向大家介绍如何运用Visual C#来一步一步创建一个文件监视的Windows服务程序,然后介绍如何安装、测试和调试该Windows服务程序。

1.创建window服务

创建完成后发现此应用程序的入口

  1. static void Main()
  2. {
  3. ServiceBase[] ServicesToRun;
  4. ServicesToRun = new ServiceBase[]
  5. {
  6. new callmeyhzService()
  7. };
  8. ServiceBase.Run(ServicesToRun);
  9. }

修改服务名称

编写服务代码

  1. public partial class callmeyhzService : ServiceBase
  2. {
  3. public callmeyhzService()
  4. {
  5. InitializeComponent();
  6. }
  7. string filePath = @"D:\MyServiceLog.txt";
  8. protected override void OnStart(string[] args)
  9. {
  10. using (FileStream stream = new FileStream(filePath,FileMode.Append))
  11. using (StreamWriter writer = new StreamWriter(stream))
  12. {
  13. writer.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss" + "服务启动!"));
  14. }
  15.  
  16. }
  17.  
  18. protected override void OnStop()
  19. {
  20.  
  21. using (FileStream stream = new FileStream(filePath, FileMode.Append))
  22. using (StreamWriter writer = new StreamWriter(stream))
  23. {
  24. writer.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss" + "服务停止!"));
  25. }
  26. }
  27. }

此时如果直接执行服务是无法安装的

2.写一个桌面应用程序管理服务

最终我们希望window服务应该在service.msc中存在

编写一个winform就放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 WindowServiceClient
  8. {
  9. public partial class Form1 : Form
  10. {
  11. public Form1()
  12. {
  13. InitializeComponent();
  14. }
  15.  
  16. string serviceFilePath = Application.StartupPath + @"\CallmeYhz.exe";
  17. string serviceName = "花生的服务";
  18.  
  19. //判断服务是否存在
  20. private bool IsServiceExisted(string serviceName)
  21. {
  22. ServiceController[] services = ServiceController.GetServices();
  23. foreach (ServiceController sc in services)
  24. {
  25. if (sc.ServiceName.ToLower() == serviceName.ToLower())
  26. {
  27. return true;
  28. }
  29. }
  30. return false;
  31. }
  32.  
  33. //卸载服务
  34. private void UninstallService(string serviceFilePath)
  35. {
  36. using (AssemblyInstaller installer = new AssemblyInstaller())
  37. {
  38. installer.UseNewContext = true;
  39. installer.Path = serviceFilePath;
  40. installer.Uninstall(null);
  41. }
  42. }
  43. //安装服务
  44. private void InstallService(string serviceFilePath)
  45. {
  46. using (AssemblyInstaller installer = new AssemblyInstaller())
  47. {
  48. installer.UseNewContext = true;
  49. installer.Path = serviceFilePath;
  50. IDictionary savedState = new Hashtable();
  51. installer.Install(savedState);
  52. installer.Commit(savedState);
  53. }
  54. }
  55.  
  56. //启动服务
  57. private void ServiceStart(string serviceName)
  58. {
  59. using (ServiceController control = new ServiceController(serviceName))
  60. {
  61. if (control.Status == ServiceControllerStatus.Stopped)
  62. {
  63. control.Start();
  64. }
  65. }
  66. }
  67.  
  68. //停止服务
  69. private void ServiceStop(string serviceName)
  70. {
  71. using (ServiceController control = new ServiceController(serviceName))
  72. {
  73. if (control.Status == ServiceControllerStatus.Running)
  74. {
  75. control.Stop();
  76. }
  77. }
  78. }
  79.  
  80. /// <summary>
  81. /// 窗体加载事件
  82. /// </summary>
  83. /// <param name="sender"></param>
  84. /// <param name="e"></param>
  85. private void Form1_Load(object sender, EventArgs e)
  86. {
  87.  
  88. }
  89.  
  90. #region 按钮事件
  91.  
  92. /// <summary>
  93. /// 安装服务按钮
  94. /// </summary>
  95. /// <param name="sender"></param>
  96. /// <param name="e"></param>
  97. private void Setep_Click(object sender, EventArgs e)
  98. {
  99. if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
  100. this.InstallService(serviceFilePath);
  101. }
  102.  
  103. /// <summary>
  104. /// 启动按钮
  105. /// </summary>
  106. /// <param name="sender"></param>
  107. /// <param name="e"></param>
  108. private void start_Click(object sender, EventArgs e)
  109. {
  110. if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
  111. }
  112.  
  113. /// <summary>
  114. /// 停止按钮
  115. /// </summary>
  116. /// <param name="sender"></param>
  117. /// <param name="e"></param>
  118. private void stop_Click(object sender, EventArgs e)
  119. {
  120. if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
  121. }
  122.  
  123. /// <summary>
  124. /// 卸载按钮
  125. /// </summary>
  126. /// <param name="sender"></param>
  127. /// <param name="e"></param>
  128. private void Union_Click(object sender, EventArgs e)
  129. {
  130. if (this.IsServiceExisted(serviceName))
  131. {
  132. this.ServiceStop(serviceName);
  133. this.UninstallService(serviceFilePath);
  134. }
  135. }
  136.  
  137. #endregion
  138. }
  139. }

先安装服务再运行服务再停止服务再写在服务

服务已经成功安装并且启动:

观察日志

说明本次小demo圆满完成

C#创建一个Window服务的更多相关文章

  1. 为MongoDB创建一个Windows服务

    一:选型,根据机器的操作系统类型来选择合适的版本,使用下面的命令行查询机器的操作系统版本 wmic os get osarchitecture 二:下载并安装 附上下载链接 点击安装包,我这里是把文件 ...

  2. 【LINUX】——linux如何使用Python创建一个web服务

    问:linux如何使用Python创建一个web服务? 答:一句话,Python! 一句代码: /usr/local/bin/python -m SimpleHTTPServer 8686 > ...

  3. ng 通过factory方法来创建一个心跳服务

    <!DOCTYPE html> <html ng-app="myApp"> <head lang="en"> <met ...

  4. C# 创建一个WCF服务

    做代码统计,方便以后使用: app.config配置文件设置: <configuration> <system.serviceModel> <bindings> & ...

  5. 使用PHP创建一个socket服务端

    与常规web开发不同,使用socket开发可以摆脱http的限制.可自定义协议,使用长连接.PHP代码常驻内存等.学习资料来源于workerman官方视频与文档. 通常创建一个socket服务包括这几 ...

  6. 在windows下创建一个Mongo服务

    首先需要下载mongo的安装包 cmd.exe 这个需要用管理员权限打开 进入到mongo的安装目录 首先到C盘根据下面的命令手动创建一个 Data 文件夹 在Data 里面创建一个db文件夹一个lo ...

  7. tomcat创建一个windows服务

    具体步骤如下: 1.把JDK解压到C:\Program Files\Java下,Tomcat解压到D:\tomcat下 2.配置环境变量 JAVA_HOME:C:\Program Files\Java ...

  8. [翻译] 使用 .NET Core 3.0 创建一个 Windows 服务

    原文: .NET Core Workers as Windows Services 在 .NET Core 3.0 中,我们引入了一种名为 Worker Service 的新型应用程序模板.此模板旨在 ...

  9. 使用PHP来简单的创建一个RPC服务

    RPC全称为Remote Procedure Call,翻译过来为"远程过程调用".主要应用于不同的系统之间的远程通信和相互调用. 比如有两个系统,一个是PHP写的,一个是JAVA ...

随机推荐

  1. C# 用程序读写另一个控制台程序

    一. using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Console.W ...

  2. Dart基础

    dartpad在线调试  :https://dartpad.dartlang.org  运行需要用墙 vscode执行dart 安装 安装dart插件 下载安装dart 配置环境变量 vscode新建 ...

  3. 模板—字符串—KMP(单模式串,单文本串)

    模板—字符串—KMP(单模式串,单文本串) Code: #include <cstdio> #include <cstring> #include <algorithm& ...

  4. 线段树【p2706】贪婪大陆

    Background 面对蚂蚁们的疯狂进攻,小FF的Tower defence宣告失败--人类被蚂蚁们逼到了Greed Island上的一个海湾.现在,小FF的后方是一望无际的大海, 前方是变异了的超 ...

  5. SPOJ IITWPC4F - Gopu and the Grid Problem (双线段树区间修改 区间查询)

    Gopu and the Grid Problem Gopu is interested in the integer co-ordinates of the X-Y plane (0<=x,y ...

  6. Jenkins一个任务下载多个git库代码

    公司的项目是微服务架构,一个服务对应的一个git仓库,现在的需求时拉取所有仓库代码下来,指定父级的pom.xml,一次性构建打包 jenkins在默认情况下,一个任务只能配置一个git仓库地址 1.安 ...

  7. centos7 启用iptables

    在centos 7下启用iptables systemctl stop firewalld.service systemctl disable firewalld.service yum instal ...

  8. 【计算几何】【斜率】bzoj1610 [Usaco2008 Feb]Line连线游戏

    枚举直线,计算斜率,排序,统计答案. #include<cstdio> #include<cmath> #include<algorithm> using name ...

  9. Exercise02_11

    import javax.swing.JOptionPane; public class Population{ public static void main(String[] args){ int ...

  10. Eclipse的workspace中放入Ext JS卡死或OOM的解决方案

    Eclipse的workspace中放入Ext JS卡死或OOM的解决方案 原因:是由于Ext JS 的所有的文件js验证 方法一:关于Eclipse解决Ext JS卡死方案: 打开Eclipse的w ...