How does one start and stop services using WMI from .NET?

Boinst picture Boinst · Oct 15, 2010 · Viewed 7.1k times · Source

How would one go about using WMI to start, stop, and query services on the local computer from .NET code? (I'm using C#)

I have found good and accurate answers for using the ServiceController class to do this, but I'd like to use WMI if I can.

Answer

Steve Townsend picture Steve Townsend · Oct 15, 2010

If you wish to use WMI over the more intuitive ServiceController class, see this article (excuse the color scheme, but it has what you want).

Sample code (error handling here is bit hard-coded for my taste):

using System.Management;

public static ReturnValue StartService(string svcName)
{
    string objPath = string.Format("Win32_Service.Name='{0}'", svcName);
    using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
    {
        try
        {
            ManagementBaseObject outParams = service.InvokeMethod("StartService",
                null, null);
            return (ReturnValue)Enum.Parse(typeof(ReturnValue),
            outParams["ReturnValue"].ToString());
        }
        catch (Exception ex)
        {
            if (ex.Message.ToLower().Trim() == "not found" || 
                ex.GetHashCode() == 41149443)
                return ReturnValue.ServiceNotFound;
            else
                throw ex;
        }
    }
}