You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过C#代码程序化添加Windows Service应用程序?

刚好之前折腾过用C#程序化添加Windows服务,给你分享两种实用的实现方式,都是我实际项目里用过的:

方法一:使用.NET Framework的ServiceInstaller组件(规范方式)

这种方式是.NET官方推荐的,适合你自己开发Windows服务的场景,能很规范地配置服务的各种属性。

首先你需要创建一个安装类,继承自Installer,把服务的配置信息写进去:

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

[RunInstaller(true)]
public class MyServiceInstaller : Installer
{
    public MyServiceInstaller()
    {
        // 配置服务运行的账户,这里选LocalSystem,你也可以根据需求换成NetworkService等
        var processInstaller = new ServiceProcessInstaller();
        processInstaller.Account = ServiceAccount.LocalSystem;

        // 配置服务的核心信息
        var serviceInstaller = new ServiceInstaller();
        serviceInstaller.ServiceName = "MyCustomService"; // 服务的唯一标识,不能重复
        serviceInstaller.DisplayName = "我的自定义服务"; // 服务列表里显示的名称
        serviceInstaller.Description = "这是通过C#代码自动安装的Windows服务"; // 服务的描述信息
        serviceInstaller.StartType = ServiceStartMode.Automatic; // 设置为自动启动

        // 把配置添加到安装器集合
        Installers.Add(processInstaller);
        Installers.Add(serviceInstaller);
    }
}

如果不想用系统的InstallUtil.exe来安装,想在自己的应用程序里直接触发安装,可以用AssemblyInstaller来执行:

using System.Configuration.Install;
using System.Reflection;

public static void InstallMyService()
{
    // 获取当前程序集的路径(如果是安装其他服务,换成对应服务的exe路径)
    string assemblyPath = Assembly.GetExecutingAssembly().Location;
    using (var installer = new AssemblyInstaller(assemblyPath, new[] { "/LogFile=" }))
    {
        installer.UseNewContext = true;
        installer.Install(null); // 执行安装操作
        installer.Commit(null); // 提交安装,确保生效
    }
}

⚠️ 重要提醒:这段代码必须以管理员权限运行,否则会直接抛出权限不足的异常,记得在启动程序时要求管理员权限。

方法二:直接调用系统sc命令(灵活方式)

如果你只是想快速实现服务安装,或者要安装第三方的服务程序,直接调用Windows自带的sc命令会更灵活,不需要依赖.NET的安装组件。

用C#的Process类来执行命令即可:

using System.Diagnostics;

public static void InstallServiceViaSc()
{
    string serviceName = "MyCustomService";
    string serviceExePath = @"C:\Full\Path\To\Your\Service.exe"; // 服务程序的绝对路径,必须是完整路径
    string displayName = "我的自定义服务";

    // 构造sc create命令,注意!参数等号后面必须跟一个空格,这是sc命令的硬性要求
    string arguments = $"create \"{serviceName}\" binPath= \"{serviceExePath}\" displayname= \"{displayName}\" start= auto";

    using (var process = new Process())
    {
        process.StartInfo.FileName = "sc.exe";
        process.StartInfo.Arguments = arguments;
        process.StartInfo.Verb = "runas"; // 强制以管理员权限启动,会弹出UAC提示
        process.StartInfo.CreateNoWindow = true; // 不显示命令行窗口
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

        process.Start();
        process.WaitForExit(); // 等待命令执行完成

        if (process.ExitCode == 0)
        {
            Console.WriteLine("服务安装成功啦!");
        }
        else
        {
            Console.WriteLine($"服务安装失败,错误码:{process.ExitCode}");
        }
    }
}

几个关键注意点:

  • sc命令的参数格式非常严格,等号后面必须加一个空格(比如binPath= "xxx"),少了空格直接执行失败,踩过这个坑的我提醒你一定要注意!
  • 如果需要给服务添加描述,可以在安装完成后再执行一句:sc description "MyCustomService" "服务的描述内容"
  • 同样需要管理员权限,这里用Verb = "runas"会自动触发UAC授权提示(如果当前用户不是管理员)

两种方式各有优劣:第一种更符合.NET的规范,适合自己开发的服务;第二种更灵活,不需要额外编写安装类,适合快速实现或安装第三方服务。

内容的提问来源于stack exchange,提问作者IsoTech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:22:15