Search code examples
c#windows-servicesrestart

How to restart Windows service programmatically?


Used ServiceController to start my Windows service from a Windows Form application. But this is not working.

ServiceController service = new ServiceController(serviceName);

This statement not working.

Is there any other way to start Windows service from my application.

Service Display Name: Duress Alert Service
Service Name: Service1

How I can restart my service in C#?

Edit 1

According to MSDN from below answer:

ServiceController sc  = new ServiceController();
sc.ServiceName = "Service1";

It shows red line under ServiceName and error:

ServiceController does not contains the definition of ServiceName. No extension method 'ServiceName' no accepting a first argument of type controller could not be found (are you missing a using directive or an assembly reference?)

While I have added the reference of service process:

using System.ServiceProcess;

But it still showing the error.


Solution

  • You will need to use the Start and Stop methods. See https://msdn.microsoft.com/en-us/library/yb9w7ytd%28v=vs.110%29.aspx for an example.