在C#中操作Windows服务通常包含创建服务程序、控制已有服务的状态以及卸载服务三大部分。借助.NET提供的System.ServiceProcess命名空间,我们可以用较少的代码完成这些任务。

一、使用C#创建Windows服务
创建服务最基础的方式是新建一个继承自ServiceBase的类,并在Main方法中调用ServiceBase.Run。下面给出一个最小可运行的服务示例。
using System.ServiceProcess;
namespace DemoService
{
public class MyService : ServiceBase
{
public MyService()
{
this.ServiceName = "MyCSharpService";
}
protected override void OnStart(string[] args)
{
// 服务启动逻辑
}
protected override void OnStop()
{
// 服务停止逻辑
}
}
public class Program
{
public static void Main()
{
ServiceBase.Run(new MyService());
}
}
}
为了让服务可被安装,还需要添加ProjectInstaller类,这里不再展开,可使用Visual Studio的服务安装器模板自动生成。
二、用ServiceController控制服务
如果服务已经存在,我们可以使用ServiceController类来启动、停止或查询状态。注意操作需要足够的系统权限。
1. 启动与停止服务
using System.ServiceProcess;
class ControlDemo
{
static void StartService(string name)
{
using (ServiceController sc = new ServiceController(name))
{
if (sc.Status == ServiceControllerStatus.Stopped)
{
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(30));
}
}
}
static void StopService(string name)
{
using (ServiceController sc = new ServiceController(name))
{
if (sc.Status == ServiceControllerStatus.Running)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, System.TimeSpan.FromSeconds(30));
}
}
}
}
2. 查询服务状态
通过Status属性可以获取当前状态,常见值有Running、Stopped、StartPending等。
using System;
using System.ServiceProcess;
class QueryDemo
{
static void PrintStatus(string name)
{
using (ServiceController sc = new ServiceController(name))
{
Console.WriteLine(sc.ServiceName + " 状态: " + sc.Status);
}
}
}
三、卸载Windows服务
除了使用InstallUtil.exe工具,也可以在代码中调用ManagedInstallerClass来卸载。下面演示用C#卸载指定服务。
using System.Configuration.Install;
class UninstallDemo
{
static void Uninstall(string servicePath)
{
// servicePath为服务程序exe路径
ManagedInstallerClass.InstallHelper(new string[] { "/u", servicePath });
}
}
四、注意事项
- 操作服务通常需要以管理员身份运行程序,否则会抛出权限异常。
- 服务名区分大小写,应与安装时设置的ServiceName一致。
- WaitForStatus可避免状态切换未完成就执行下一步导致报错。
使用C#操作Windows服务并不复杂,掌握ServiceBase与ServiceController即可应对大多数场景。
通过上述示例,你可以完成C#对Windows服务的创建、启动、停止和卸载。实际项目中建议将服务逻辑与安装卸载脚本分离,便于维护。
C#Windows服务ServiceController修改时间:2026-07-25 15:21:25