Home > Programming > Get Windows Service info in C#.

Get Windows Service info in C#.

January 23rd, 2010 Jimmy Leave a comment Go to comments

This code will show you how to search for Windows Services. The ServiceController class handles almost everything service related. You can also check if services are running by checking the service.Status property and you can search for installed services using the sample code below. The services we are talking about are the services that run in the Background in Windows. These include things like web servers, authentication services, printing services etc..

Availible Status’s

    public enum ServiceControllerStatus
    {

// The service is not running.
       Stopped = 1,

//     The service is starting.
       StartPending = 2,

//     The service is stopping.
        StopPending = 3,

 //     The service is running.
        Running = 4,

//     The service continue is pending.
         ContinuePending = 5,

//     The service pause is pending.
         PausePending = 6,

//  The service is paused.
         Paused = 7,
    }

Sample Windows Services Code (C#).

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceProcess;

namespace CodePLayground
{
    class WinServices
    {
        public bool isServiceInstalled(string svcName)
        {
            ServiceController[] services = ServiceController.GetServices();

            //Loop through all the services.
            foreach (ServiceController service in services)
            {
                //see if the service we are looking for is in the Service Name?
                if (service.DisplayName.Contains(svcName))
                    return true;

                //well we better check the ServiceName as well which is not the same as the display name.
                if(service.ServiceName.Contains(svcName))
                    return true;
            }
            return false;
          }

        public bool isServiceRunning(string svcName)
        {
            ServiceController[] services = ServiceController.GetServices();

            //Loop through all the services.
            foreach (ServiceController service in services)
            {
                //see if the service we are looking for is in the Service Name? If so, check status, if all checks out return true.
                if ((service.DisplayName.Contains(svcName)) && (service.Status == ServiceControllerStatus.Running))
                    return true;
            }
            return false;
        }

      }
}
Digg: DIGG ME
  1. No comments yet.
  1. April 20th, 2010 at 02:13 | #1