Search code examples
c#windowsserviceservicecontroller

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


Hi I'm trying to change the startup type of a existing Windows service. Say "Spooler" ( Print Spooler). I'm using ServiceController

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

Though I'm able to start/stop services I'm not able to figure out how can I change the startup type itself? ( eg: Disabled/Automatic/Manual ) enter image description here

When I peek definition of ServiceController I can see ServiceStartMode being defined. Could someone help me how can I set this option?. My need is to disable a Windows service programmatically using ServiceControl class or any other feasible way..


Solution

  • 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).