beta.blog

C# – Get Startup Type of a Service (Windows)

by 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

[csharp]
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>";
}
}
[/csharp]


5 Comments for this entry

  • Leif Nomeland

    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?

  • itsho

    Hi. great code !.

    just a small remark:
    Line 18 is redundant – the ManagementObjectSearcher ctor will never return null.

  • TomB

    @Leif
    object[] parameters = new object[1];
    parameters[0] = “Auto”;
    service.InvokeMethod(“ChangeStartMode”, parameters);

  • mil

    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” ??

  • Bruno

    Thanks!! Super useuful!!

Leave a Reply

*

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!