簡體   English   中英

如何在 C# 中以編程方式將 Windows 服務的啟動類型更改為 Disabled

[英]How to change the startup type of Windows service to Disabled programmatically in C#

您好我正在嘗試更改現有 Windows 服務的啟動類型。 說“Spooler”(打印后台處理程序)。 我正在使用ServiceController

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

雖然我能夠啟動/停止服務,但我無法弄清楚如何更改啟動類型本身? (例如:禁用/自動/手動) 在此處輸入圖像描述

當我查看ServiceController的定義時,我可以看到ServiceStartMode正在定義。 有人可以幫我如何設置此選項嗎? 我需要使用 ServiceControl class 或任何其他可行的方式以編程方式禁用 Windows 服務。

最簡單的方法是使用sc 命令工具

將啟動類型更改為禁用的示例:

sc config "MySql" start=disabled

請注意,您需要具有管理員權限才能成功運行此命令。

用 C# 代碼包裝:

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}");
}

更新:使用process.Exit代碼檢查處理操作是否成功。 0 ExitCode成功。

注意:如果您在沒有管理員權限的情況下運行進程/Visual Studio, ExitCode將為 5(訪問定義)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM