Window服务介绍

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

1.创建window服务

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

 static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new callmeyhzService()
};
ServiceBase.Run(ServicesToRun);
}

修改服务名称

编写服务代码

  public partial class callmeyhzService : ServiceBase
{
public callmeyhzService()
{
InitializeComponent();
}
string filePath = @"D:\MyServiceLog.txt";
protected override void OnStart(string[] args)
{
using (FileStream stream = new FileStream(filePath,FileMode.Append))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss" + "服务启动!"));
} } protected override void OnStop()
{ using (FileStream stream = new FileStream(filePath, FileMode.Append))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss" + "服务停止!"));
}
}
}

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

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

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

编写一个winform就放4个按钮

上代码

using System;
using System.Collections;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Configuration.Install; namespace WindowServiceClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} string serviceFilePath = Application.StartupPath + @"\CallmeYhz.exe";
string serviceName = "花生的服务"; //判断服务是否存在
private bool IsServiceExisted(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController sc in services)
{
if (sc.ServiceName.ToLower() == serviceName.ToLower())
{
return true;
}
}
return false;
} //卸载服务
private void UninstallService(string serviceFilePath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
installer.Uninstall(null);
}
}
//安装服务
private void InstallService(string serviceFilePath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
IDictionary savedState = new Hashtable();
installer.Install(savedState);
installer.Commit(savedState);
}
} //启动服务
private void ServiceStart(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Stopped)
{
control.Start();
}
}
} //停止服务
private void ServiceStop(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Running)
{
control.Stop();
}
}
} /// <summary>
/// 窗体加载事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{ } #region 按钮事件 /// <summary>
/// 安装服务按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Setep_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
this.InstallService(serviceFilePath);
} /// <summary>
/// 启动按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void start_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
} /// <summary>
/// 停止按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void stop_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
} /// <summary>
/// 卸载按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Union_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
{
this.ServiceStop(serviceName);
this.UninstallService(serviceFilePath);
}
} #endregion
}
}

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

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

观察日志

说明本次小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. 肖申克的救赎 -Hope

    典狱长诺顿高高在上,平时道貌岸然,对圣经倒背如流,实际上攫取利益时不择手段,残酷.阴险而贪婪.狱警长海利和其他警员,凶狠残暴,充当诺顿的打手,草菅囚犯的人命.他们是不是象极了我们现实中的掌权阶层?我称 ...

  2. 洛谷——P1722 矩阵 II

    P1722 矩阵 II 题目背景 usqwedf 改编系列题. 题目描述 如果你在百忙之中抽空看题,请自动跳到第六行. 众所周知,在中国古代算筹中,红为正,黑为负…… 给定一个1*(2n)的矩阵(us ...

  3. 洛谷——P1689 方程求解

    P1689 方程求解 题目描述 给一个方程,形如X+Y=Z或X-Y=Z.给出了其中两个未知数,请求出第三个数.未知数用‘?’表示,等式中也许会出现一些多余的空格. 输入输出格式 输入格式: 一行,方程 ...

  4. [Luogu P4198]楼房重建(线段树)

    题目描述 小A的楼房外有一大片施工工地,工地上有N栋待建的楼房.每天,这片工地上的房子拆了又建.建了又拆.他经常无聊地看着窗外发呆,数自己能够看到多少栋房子. 为了简化问题,我们考虑这些事件发生在一个 ...

  5. 【树链剖分】【dfs序】【线段树】bzoj2836 魔法树

    这道题告诉我们:树链剖分的重标号就是dfs序. #include<cstdio> #include<algorithm> using namespace std; #defin ...

  6. 【DFS序】【莫队算法】【权值分块】bzoj2809 [Apio2012]dispatching

    题意:在树中找到一个点i,并且找到这个点子树中的一些点组成一个集合,使得集合中的所有点的c之和不超过M,且Li*集合中元素个数和最大 首先,我们将树处理出dfs序,将子树询问转化成区间询问. 然后我们 ...

  7. [CF915F]Imbalance Value of a Tree

    [CF915F]Imbalance Value of a Tree 题目大意: 一棵\(n(n\le10^6)\)个结点的树,每个结点有一个权值\(w_i\).定义\(I(i,j)\)为\(i\)到\ ...

  8. Exercise03_02

    import java.util.Scanner; public class AdditionQuiz { public static void main(String[] args){ int nu ...

  9. dubbo安装(转载)

    1.   概述 ZooKeeper是Hadoop的正式子项目,它是一个针对大型分布式系统的可靠协调系统,提供的功能包括:配置维护.名字服务.分布式同步.组服务等.ZooKeeper的目标就是封装好复杂 ...

  10. C语言实现括号配对问题

    代码如下: #include<stdio.h> #include<string.h> #include<stdlib.h> // 写一个判断的括号是否匹配的函数 i ...