C# – Get Startup Type of a Service (Windows)
by admin on Feb.16, 2012, under Programming
The following example code demonstrates how to determine the StartMode of a Windows Service. You need to add a reference to System.Management.dll and
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management; class ServiceController { public static string GetServiceStartMode(string serviceName) { uint success = 1; string filter = String.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName); ManagementObjectSearcher query = new ManagementObjectSearcher(filter); // No match = failed condition if (query == null) return "<null>"; try { ManagementObjectCollection services = query.Get(); foreach (ManagementObject service in services) { return service.GetPropertyValue("StartMode").ToString() == "Auto" ? "Automatic" : "Manual"; } } catch (Exception ex) { return "<null>"; } return "<null>"; } }
July 3rd, 2012 on 15:51
Is there anyway to set the startmode to a different value? You can do:
service.SetPropertyValue(“StartMode”, ServiceStartMode.Manual) but this actually doesn’t make the change, anyway to do this?
August 18th, 2012 on 22:07
Hi. great code !.
just a small remark:
Line 18 is redundant – the ManagementObjectSearcher ctor will never return null.
April 11th, 2013 on 16:51
@Leif
object[] parameters = new object[1];
parameters[0] = “Auto”;
service.InvokeMethod(“ChangeStartMode”, parameters);
June 4th, 2013 on 10:06
Thanks for the code!
but i have one question:
is there any possibility to check if the startup type of a service is “auto-delayed” ??
July 14th, 2016 on 21:32
Thanks!! Super useuful!!