beta.blog

Programming

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

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>";
    }
}
5 Comments more...

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!