当前位置:首页 > C# > 正文

C# Windows服务安装与卸载完整教程(手把手教你部署和移除Windows服务)

在Windows系统中,Windows服务是一种在后台运行的长期进程,常用于执行定时任务、监听端口或处理系统事件等。使用C#语言开发Windows服务非常常见,但很多初学者在安装与卸载环节遇到困难。本教程将手把手带你完成整个流程,即使是编程小白也能轻松上手!

C# Windows服务安装与卸载完整教程(手把手教你部署和移除Windows服务) Windows服务安装 Windows服务卸载 Windows服务开发教程 C#服务部署指南 第1张

一、准备工作

在开始之前,请确保你已安装以下工具:

  • Visual Studio(推荐2019或更高版本)
  • .NET Framework 或 .NET(根据你的项目选择)
  • 管理员权限的命令提示符(CMD)或 PowerShell

二、创建一个简单的Windows服务项目

打开 Visual Studio,选择“创建新项目” → 搜索“Windows Service”,选择对应模板(如“.NET Framework Windows Service”)。

创建完成后,你会看到一个继承自 ServiceBase 的类。为了支持安装,我们还需要添加一个安装程序类

添加服务安装程序

右键项目 → 添加 → 新建项 → 选择“安装程序类”。默认会生成一个 ProjectInstaller.cs 文件。

双击打开设计器,你会看到两个组件:serviceInstallerserviceProcessInstaller。设置它们的属性如下:

// ProjectInstaller.csusing System.ComponentModel;using System.Configuration.Install;using System.ServiceProcess;[RunInstaller(true)]public partial class ProjectInstaller : Installer{    private ServiceInstaller serviceInstaller;    private ServiceProcessInstaller processInstaller;    public ProjectInstaller()    {        // 初始化安装组件        serviceInstaller = new ServiceInstaller();        processInstaller = new ServiceProcessInstaller();        // 设置服务名称和显示名称        serviceInstaller.ServiceName = "MyTestService";        serviceInstaller.DisplayName = "我的测试服务";        serviceInstaller.Description = "这是一个用C#编写的示例Windows服务";        // 设置服务账户(LocalSystem拥有最高权限)        processInstaller.Account = ServiceAccount.LocalSystem;        // 将安装程序添加到集合中        Installers.Add(serviceInstaller);        Installers.Add(processInstaller);    }}

三、编译项目

点击“生成” → “生成解决方案”。成功后,在项目的 bin\Debugbin\Release 目录下会生成一个 .exe 文件(例如 MyService.exe)。

四、安装Windows服务

管理员身份打开命令提示符(CMD)或 PowerShell,进入你的服务可执行文件所在目录,然后使用 InstallUtil.exe 工具进行安装。

REM 进入目录(根据你的实际路径修改)cd "C:\YourProject\bin\Debug"REM 安装服务"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe" MyService.exe

如果看到“正在提交安装事务...”和“安装成功完成”的提示,说明服务已成功安装。

你可以在“服务”管理控制台(services.msc)中找到你的服务,并手动启动它。

五、卸载Windows服务

卸载同样使用 InstallUtil.exe,只需加上 /u 参数:

REM 卸载服务"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe" /u MyService.exe

卸载成功后,服务将从系统中彻底移除。

六、常见问题与注意事项

  • 务必使用管理员权限运行命令提示符,否则会因权限不足失败。
  • 确保 InstallUtil.exe 路径正确。如果你使用的是 .NET Core/.NET 5+,则需改用 sc.exe 或第三方工具(如 NSSM)。
  • 服务安装后默认是“手动启动”,如需开机自启,可在代码中设置 serviceInstaller.StartType = ServiceStartMode.Automatic;
  • 调试服务时建议先以控制台程序方式运行,避免反复安装/卸载。

七、总结

通过本教程,你已经掌握了使用 C# 开发 Windows 服务后的安装与卸载方法。无论是 C# Windows服务安装 还是 C# Windows服务卸载,核心都在于正确使用 InstallUtil.exe 工具和编写规范的安装程序类。

希望这篇 Windows服务开发教程C#服务部署指南 能帮助你顺利部署自己的后台服务!如有疑问,欢迎在评论区留言交流。