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.

Community
  • 1
  • 1
Boinst
  • 3,365
  • 2
  • 38
  • 60
  • 1
    *Can* WMI do this? Is there an issue with using the ServiceController class? Certainly WMI can tell you about a service in terms of being an executing process- and from there you could start()/terminate() the process, but this seems like you're skipping a perfectly obvious layer of abstraction by choosing not to use the ServiceController class. Note: Please correct me if I'm horribly wrong here! – Nathan Taylor Oct 15 '10 at 00:36
  • @nathan-taylor, you're right, ServiceController is much cleaner, I might switch to that at a later stage. – Boinst Oct 15 '10 at 02:12

1 Answers1

6

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
  • 53,498
  • 9
  • 91
  • 140