views:

22

answers:

1

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.

+1  A: 

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;
        }
    }
}
Steve Townsend
Thanks Steve, that code on CodeProject does exactly what I asked for.
Boinst