0

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

SKN
  • 520
  • 1
  • 5
  • 20
  • Does this answer your question? [How to stop Windows service programmatically](https://stackoverflow.com/questions/16317378/how-to-stop-windows-service-programmatically) – evry1falls May 13 '20 at 01:12
  • You may want to look at the answers at [Disable Windows service at application launch](https://stackoverflow.com/questions/3052649/disable-windows-service-at-application-launch) – Bryson May 13 '20 at 07:32

1 Answers1

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

Community
  • 1
  • 1
EylM
  • 5,967
  • 2
  • 16
  • 28
  • Thanks for this. In fact I had tried this already. The problem I see here is, after process.Start(), when I inspect process object, I saw InvalidOperationException. So I couldn't rely on "HasExited" property of Process , to determine if the operation was successful or not – SKN May 13 '20 at 07:14