0

您好我正在尝试更改现有 Windows 服务的启动类型。说“Spooler”(打印后台处理程序)。我在用着ServiceController

   var service = new ServiceController("Spooler");
                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running, 600);

虽然我能够启动/停止服务,但我无法弄清楚如何更改启动类型本身?(例如:禁用/自动/手动)在此处输入图像描述

当我查看定义时,ServiceController我可以看到ServiceStartMode 被定义。有人可以帮我如何设置此选项吗?我的需要是使用 ServiceControl 类或任何其他可行的方式以编程方式禁用 Windows 服务..

4

1 回答 1

1

The simplest way is to use a sc command tool:

Example for changing the startup type to disabled:

sc config "MySql" start=disabled

Note you need to have the administrator privileges to run this command successfully.

Wrapping with C# code:

var startInfo = new ProcessStartInfo
{               
    WindowStyle = ProcessWindowStyle.Hidden,
    FileName = "CMD.EXE",
    Arguments = string.Format("/C sc {0} {1} {2}", "config", "MySql", "start=disabled"),
};

using (var process = new Process { StartInfo = startInfo})
{
    if (!process.Start())
    {
        return;
    }

    process.WaitForExit();

    Console.WriteLine($"Exit code is {process.ExitCode}");
}

Update: Use process.Exit code to check if process the operation succeeded or not. 0 ExitCode is success.

Note: In case you are running the process/Visual Studio without the Admin privileges, the ExitCode will be 5 (access deined).

于 2020-05-12T18:50:23.340 回答