如何使用 C# 中的 Windows 命令提示符安装 Windows 服务?
步骤 1 −
创建一个新的 Windows 服务应用程序。

步骤 2 −
若要运行 Windows 服务,你需要安装 Installer,该 Installer 会将其注册到服务控制管理器。右键单击 Service1.cs[设计]并添加安装程序。


步骤 3 −
右键单击 ProjectInstaller.cs [设计]并选择查看代码。

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Threading.Tasks;
namespace DemoWindowsService{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer{
public ProjectInstaller(){
InitializeComponent();
}
}
}按 F12 并转至 InitializeComponent 类的实现。添加将在安装过程中成为 Windows 服务名称的名称和描述。
private void InitializeComponent(){
this.serviceProcessInstaller1 = new
System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account =
System.ServiceProcess.ServiceAccount.LocalService;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// serviceInstaller1
//
this.serviceInstaller1.Description = "My Demo Service";
this.serviceInstaller1.ServiceName = "DemoService";
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}步骤 4 −
现在让我们在 Service1.cs 类中添加以下逻辑,以便在文本文件中写入日志数据。
using System;
using System.IO;
using System.ServiceProcess;
using System.Timers;
namespace DemoWindowsService{
public partial class Service1 : ServiceBase{
Timer timer = new Timer();
public Service1(){
InitializeComponent();
}
protected override void OnStart(string[] args){
WriteToFile("Service started at " + DateTime.Now);
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 5000;
timer.Enabled = true;
}
protected override void OnStop(){
WriteToFile("Service stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e){
WriteToFile("Service recall at " + DateTime.Now);
}
public void WriteToFile(string Message){
string path = @"D:\Demo";
if (!Directory.Exists(path)){
Directory.CreateDirectory(path);
}
string filepath = @"D:\Demo\Log.txt";
if (!File.Exists(filepath)){
using (StreamWriter sw = File.CreateText(filepath)){
sw.WriteLine(Message);
}
} else {
using (StreamWriter sw = File.AppendText(filepath)){
sw.WriteLine(Message);
}
}
}
}
}步骤 5(安装)−
现在我们使用命令提示符安装 Windows 服务。以管理员身份打开命令提示符并提供以下命令。
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

打开我们 Windows 服务 exe 文件所在的文件夹,运行以下命令。
InstallUtil.exe C:\Users\[UserName] source\repos\DemoWindowsService\DemoWindowsService\bin\Debug\ DemoWindowsService.exe


现在从 Windows 应用程序菜单打开服务。


我们可以看到我们的 Windows 服务已安装并且如期运行。
以下输出表明该服务正在运行并将日志按预期写入文本文件。

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP