In the same vein as my last post on how to programmatically update a service startup type, here’s how one might determine if a service is currently stopped in C#:

using System.Management;
/// <summary>
/// This routine checks if the provided service is stopped.
/// </summary>
/// <param name="serviceName">Name of the service to be checked</param>
/// <param name="errorMsg">If applicable, error message assoicated with exception</param>
/// <returns>Stopped = true else false</returns>
public static bool IsServiceStopped(string serviceName, out string errorMsg)
{
    bool isStopped = false;
    errorMsg = string.Empty;

    string filter =
        String.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName);

    ManagementObjectSearcher query = new ManagementObjectSearcher(filter);

    // No match = stopped
    if (query == null) return false;

    try
    {
        ManagementObjectCollection services = query.Get();

        foreach (ManagementObject service in services)
        {
            string currentStatus = Convert.ToString(service["State"]);
            isStopped = (currentStatus.ToLower() == "stopped");
        }
    }
    catch (Exception ex)
    {
        errorMsg = ex.Message;
        throw;
    }

    return isStopped;
}

kick it on DotNetKicks.com

3 Comments to “Check Status of Windows Service”

  1. Kai says:


    // No match = stopped
    if (query == null) return false;

    Sorry to nit pick but shouldnt this be


    // No match = stopped
    if (query == null) return true;

  2. Ben says:

    Thanks for the comment. I completely understand your view point. If the service is not found (it doesn’t exist) it isn’t running so it is basically stopped. I considered this, but went with false as I thought it was most appropriate in the context of the routine. Basically, I can’t confirm the stopped state of the service so I returned false. I think I’ll make the change. Thanks again for the feedback.

  3. Arindam says:

    /////////////////////////////////////////////////////////////
    //Please see my small health checking application code
    /////////////////////////////////////////////////////////////

    public class StatusChecker
    {
    private bool IsEventInWindow(int windowSizeMinutes, string LogSource, string serviceName)
    {
    EventLog eventLog = new EventLog { Source = LogSource };
    EventLogEntryCollection entries = eventLog.Entries;
    try
    {
    foreach (EventLogEntry entry in entries)
    {
    if ((entry.TimeWritten > DateTime.Now.AddMinutes(-windowSizeMinutes) && entry.Source == serviceName) ||
    (entry.TimeWritten > DateTime.Now.AddMinutes(-windowSizeMinutes) && entry.Source == LogSource))
    {
    return true;
    }
    }
    }
    catch (Exception e)
    {
    Util.WriteLog(e, LogSource);
    }
    finally
    {
    if (eventLog != null)
    {
    eventLog.Dispose();
    }
    if (entries != null)
    {
    entries = null;
    }
    }
    return false;
    }

    private bool IsServiceRunning(string LogSource)
    {
    try
    {
    ServiceController sc = new ServiceController(LogSource);
    return sc.Status == ServiceControllerStatus.Running;
    }
    catch (Exception e)
    {
    Util.WriteLog(e, LogSource);
    }
    return false;
    }
    public bool IsServiceOk(string serviceName, string logSource)
    {
    string filter = String.Format(“SELECT * FROM Win32_Service WHERE Name = ‘{0}’”, serviceName);
    ManagementObjectSearcher query = new ManagementObjectSearcher(filter);
    if (query == null)
    {
    return false;
    }
    try
    {
    ManagementObjectCollection services = query.Get();
    foreach (ManagementObject service in services)
    {
    if (Convert.ToString(service["State"]).ToLower() == “running”)
    {
    return true;
    }
    }
    }
    catch (Exception ex)
    {
    Util.WriteLog(ex, logSource);
    }
    return false;
    }
    public bool ServiceCheck(int windowSizeMinutes, string logSource, string serviceName)
    {
    try
    {
    if (IsServiceRunning(serviceName) && IsServiceOk(serviceName,logSource) && IsEventInWindow(windowSizeMinutes, logSource, serviceName))
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    catch (Exception ex)
    {
    Util.WriteLog(ex, logSource);
    return false;
    }
    }
    }

    //////////////////////////////////////////////////////////////////main function//////
    ///////////////////////////////////////////////////////////////

    private static void Main(string[] args)
    {
    int window = 15;
    string LogSource = null;
    string ServiceName = null;
    try
    {

    if (args[0] != null && !String.IsNullOrEmpty(args[0]))
    {
    ServiceName = args[0].Trim();
    }
    if (args[1] != null && !String.IsNullOrEmpty(args[1]))
    {
    LogSource = args[1].Trim();
    }
    if (args[2] != null && !String.IsNullOrEmpty(args[2]))
    {
    window = Int32.Parse(args[2]);
    }
    }
    catch (Exception e)
    {
    Console.Out.WriteLine(“Please check the argument that you supplied \r\nYou have to supply the service name,log source and log scanning window (in minutes which is optional but should be integer) \r\nas an argument to this command.”);
    }
    StatusChecker checker = new StatusChecker();
    if (!checker.ServiceCheck(window, LogSource, ServiceName))
    {
    Console.Out.WriteLine(“CRITICAL ## ” + ServiceName + ” service not running on this node \\ hanged state.”);
    Environment.Exit(1);
    }
    else
    {
    Console.Out.WriteLine(“OK##”);
    Environment.Exit(0);
    }
    }

Leave a Reply

You can wrap your code with [ruby][/ruby] or [python][/python] blocks for syntax highlighting and you can use these traditional tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>