Manage Windows Services using C#

In this post, we’ll explore how to programmatically Manage Windows Services using C#. This includes starting, stopping, pausing, and checking the status of services through the .NET framework.

Prerequisites
To follow along, you’ll need:
  • Visual Studio or any C# development environment
  • .NET Framework or .NET Core/5+/6+
  • Administrator privileges (to control services)

Manage Windows Services using C#

Getting Started

Windows Services are long-running executable applications that operate in their own Windows sessions and can be configured to start automatically when the system boots. They are well-suited for tasks that run in the background without user interaction, such as logging, monitoring, and other continuous processes.

To Manage Windows Services using C#, we will be needed a namespace System.ServiceProcess. C# provides this namespace which includes classes to manage Windows Services. Hence insure that you have included the this along with system namespace like below.

 using System;  
 using System.ServiceProcess;  

Manage Windows Services

As mentioned in the introduction, managing Windows Services involves starting, stopping, pausing, and checking the status of services using the .NET framework. This post demonstrates how to perform each of these operations programmatically.

Listing All Services
static void listingServices()
{
    ServiceController[] services = ServiceController.GetServices();
    foreach (var service in services)
    {
        Console.WriteLine($"{service.ServiceName} - {service.DisplayName}");
    }
}

Finding A Services
static void findService(string serviceName)
{
    ServiceController service = new ServiceController("YourServiceName");
    Console.WriteLine($"{service.ServiceName} - {service.DisplayName}");
}    

Starting a Service
static void StartService(string serviceName, int timeoutMilliseconds)
{
    ServiceController service = new ServiceController(serviceName);
    try
    {
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, timeout);

        Console.WriteLine("Service started successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error starting service: {ex.Message}");
    }
}   

Stopping a Service

  static void StopService(string serviceName, int timeoutMilliseconds)
{
    ServiceController service = new ServiceController(serviceName);
    try
    {
        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

        service.Stop();
        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

        Console.WriteLine("Service stopped successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error stopping service: {ex.Message}");
    }
}

Pausing a Service
static void PauseService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    if (service.CanPauseAndContinue)
    {
        service.Pause();
        service.WaitForStatus(ServiceControllerStatus.Paused);
        Console.WriteLine("Service paused.");
    }
    else
    {
        Console.WriteLine("Service cannot be paused.");
    }
}

Continuing a Service
static void ContinueService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    if (service.CanPauseAndContinue)
    {
        service.Continue();
        service.WaitForStatus(ServiceControllerStatus.Running);
        Console.WriteLine("Service resumed.");
    }
    else
    {
        Console.WriteLine("Service cannot be resumed.");
    }
}

Checking Service Status
static void CheckServiceStatus(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    Console.WriteLine($"Service {service.ServiceName} is {service.Status}");
}

Example Usage
static void Main(string[] args)
{
    string serviceName = "MSSQLSERVER"; // Example: SQL Service

    CheckServiceStatus(serviceName);
    StopService(serviceName, 10000);
    StartService(serviceName, 10000);
    PauseService(serviceName);
    ContinueService(serviceName);
}

Note:-
  • To manage most Windows services, the application must be run with administrative privileges.
  • Use exception handling to catch InvalidOperationException, Win32Exception, etc.
  • Use ServiceControllerPermission if you’re working with partially trusted code.
  • Check service.CanStop, service.CanPauseAndContinue before invoking actions.

Full Console Code

The below are the full source code fo the console application for managing windows services.You can copy the codes and replace with your console application project code.

using System;
using System.ServiceProcess;

namespace ManageWindowsService
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string serviceName = "MSSQLSERVER"; // Example: SQL Service

            CheckServiceStatus(serviceName);
            StopService(serviceName, 10000);
            StartService(serviceName, 10000);
            PauseService(serviceName);
            ContinueService(serviceName);
        }
        static void findService(string serviceName)
        {
            ServiceController service = new ServiceController("YourServiceName");
            Console.WriteLine($"{service.ServiceName} - {service.DisplayName}");
        }
        static void listingServices()
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (var service in services)
            {
                Console.WriteLine($"{service.ServiceName} - {service.DisplayName}");
            }
        }
        static void StartService(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);

                Console.WriteLine("Service started successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error starting service: {ex.Message}");
            }
        }
        static void StopService(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

                Console.WriteLine("Service stopped successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error stopping service: {ex.Message}");
            }
        }
        static void PauseService(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);
            if (service.CanPauseAndContinue)
            {
                service.Pause();
                service.WaitForStatus(ServiceControllerStatus.Paused);
                Console.WriteLine("Service paused.");
            }
            else
            {
                Console.WriteLine("Service cannot be paused.");
            }
        }
        static void ContinueService(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);
            if (service.CanPauseAndContinue)
            {
                service.Continue();
                service.WaitForStatus(ServiceControllerStatus.Running);
                Console.WriteLine("Service resumed.");
            }
            else
            {
                Console.WriteLine("Service cannot be resumed.");
            }
        }
        static void CheckServiceStatus(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);
            Console.WriteLine($"Service {service.ServiceName} is {service.Status}");
        }

    }
}

Summary

Managing Windows Services Using C# is straightforward with the help of the System.ServiceProcess namespace. Whether you're developing tools for automation, diagnostics, or custom service monitoring, the ability to control services programmatically offers significant flexibility and power.

Thanks

Kailash Chandra Behera

An IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies. Demonstrated expertise in delivering all phases of project development—from initiation to closure—while aligning with business objectives to drive process improvements, competitive advantage, and measurable bottom-line gains. Proven ability to work independently and manage multiple projects successfully. Committed to the efficient and effective development of projects in fast-paced, deadline-driven environments. Skills: Proficient in designing and developing applications using various Microsoft technologies. Total IT Experience: 13+ years

Previous Post Next Post

نموذج الاتصال