Home > C# Class, Development > C# Start/Stop/Restart Windows Service Remotely or Locally

C# Start/Stop/Restart Windows Service Remotely or Locally

May 13th, 2011

Below is a very basic implementation of a class that runs within a Windows Form, to Start, Stop and Restart a windows service.

I have not included checking for other service states other than Started and Stopped, this could be extended. If you are using this to control a windows service on a remote PC, you need to ensure that the user account you are executing this from has high enough privileges to Start and Stop a service.

Updated Download of Sourcecode

Edited: 13th May 2011 –> After some imperfections, I have updated the code as shown below and in the download link above.

Fields and Constructors of Class


private const int RestartTimeout = 10000;

private readonly ServiceController service;

public Control(string serviceName, string computerName)
{
    service = new ServiceController(serviceName, computerName);
}

public Control(string serviceName)
{
    service = new ServiceController(serviceName);
}

Start Windows Service:


public bool StartService()
{
    try
    {
        service.Refresh();

        if (service.Status == ServiceControllerStatus.Stopped)
        {
            service.Start();
            return true;
        }

        MessageBox.Show(string.Format("{0} --> already started", service.DisplayName));
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString(), @"Error Starting Service");
    }

    return false;
}

Stop Windows Service:


public bool StopService()
{
    try
    {
        service.Refresh();

        if (service.Status == ServiceControllerStatus.Running)
        {
            service.Stop();
            return true;
        }

        MessageBox.Show(string.Format("{0} --> already stopped", service.DisplayName));
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString(), @"Error Stopping Service");
    }

    return false;
}

Restart Windows Service


public bool RestartService()
{
    try
    {
        service.Refresh();

        if (service.Status != ServiceControllerStatus.Stopped)
        {
            service.Stop();

            int i = 0;
            while (service.Status != ServiceControllerStatus.Stopped)
            {
                service.Refresh();
                Thread.Sleep(100);
                i++;

                if (i >= RestartTimeout / 100)
                {
                    MessageBox.Show(@"Restart Stop Timeout Exceeded");
                    return false;
                }
            }

            service.Start();
            return true;
        }

        service.Start();
        MessageBox.Show(string.Format("{0} --> was stopped, service has been started", service.DisplayName));
        return true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString(), @"Error Restarting Service");
        return false;
    }
}

  1. May 13th, 2011 at 03:02 | #1

    Hi. Your code looks good, except for a bug in RestartService():

    > if (service.Status == ServiceControllerStatus.Stopped)

    should probably be:

    > if (service.Status != ServiceControllerStatus.Stopped)

    BTW, some folks may expect Restart() to work like Start() if a service is stopped…

    http://ww.CoreTechnologies.com
    “Experts in Windows Services”

  2. May 13th, 2011 at 09:45 | #2

    @CoreTech
    Cheers for the advice, I have made this adjustment on the post. Will update the attached cs file later tonight.

  3. csXen
    March 3rd, 2012 at 08:33 | #3

    Hi – Your code makes some poor assumptions, which CoreTech has recently pointed out. Your start/stop/restart methods are all flawed because of the lack of accounting for other service states and your explicit evaluation. Your code should be more flexible.

    None of these states are accounted for:

    ServiceControllerStatus.StopPending
    ServiceControllerStatus.StartPending
    ServiceControllerStatus.ContinuePending
    ServiceControllerStatus.PausePending
    ServiceControllerStatus.Paused

    You have also neglected to leverage the WaitForStatus method.

    In a nutshell, your explicit calls to evaluate service state cause these methods to be unreliable.

    For instance, when restarting a service, it should not matter if the service is in the stopped state already. It should determine the current state, manage it, then issue the appropriate command to start the service, not just stop and return false.

  4. February 6th, 2013 at 16:11 | #4

    This article is truly a fastidious one it assists new web users, who are
    wishing in favor of blogging.

  5. ganesh
    November 19th, 2013 at 18:10 | #5

    service stop perfectly but not start again in RestartService () method plz give me the solution

Comments are closed.
%d bloggers like this: