Archive

Posts Tagged ‘remotely’

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

May 13th, 2011 5 comments

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;
    }
}

%d bloggers like this: