2

I'm looking for a C# version of the following command:

sc config "someServiceName" start=auto

I've found a lot of information about configuring a service to start automatically as you install it, but I'm having trouble finding out how to do the same for an existing service.

Right now, I've resorted to shelling it out, but if there's a way to use .NET APIs, I'd much rather do that.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574

2 Answers2

6

This should do the trick:

var serviceName = "<your service name here>";
string objPath = string.Format("Win32_Service.Name='{0}'", serviceName);
using (var service = new ManagementObject(new ManagementPath(objPath)))
{
    var result = (int)service.InvokeMethod("ChangeStartMode", new object[] {"Automatic"});
}

You'll need to add a reference to the System.Management assembly, as well as import the namespace System.Management.

Note that your program must elevated (running as an Administrator) for this to work, and there is no way around that. For other possible values for ChangeStartMode, you can refer to MSDN.

The result variable will be a numeric value that indicates the result. For example, 0 for Success. Refer the the previously linked MSDN article for all of the possible return values.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
-1
var serviceName = "<your service name here>";
string objPath = string.Format("Win32_Service.Name='{0}'", serviceName);
using (var service = new ManagementObject(new ManagementPath(objPath)))
{
    service.InvokeMethod("ChangeStartMode", new object[] {"Automatic"});
}

You'll need to add a reference to the System.Management assembly, as well as import the namespace System.Management.

IAmInPLS
  • 4,051
  • 4
  • 24
  • 57