You can use the below methods for the same:-
Add the System.ServiceProcess reference form solution window.
using System.ServiceProcess;
public void StartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
if (Convert.ToString(service.Status) == "Stopped")
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
//"Service is Successfully Started.
}
//else
//Service is Already started
}
public void StopService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
if (Convert.ToString(service.Status) == "Running")
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
lblErrorMsg.Text = "Service is Successfully Stopped.";
}
//else
//Service is Already Stopped
}
public void RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
if (Convert.ToString(service.Status) == "Running")
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
//Service is Successfully Stopped.
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
//Service is Successfully ReStarted.
}
//else
//Service is Currently Stopped. You Can't Re-Start the Service.
}
How to call the service form you page:-
StartService(_ServiceName, 30000);
StopService(_ServiceName, 30000);
RestartService(_ServiceName, 30000);
Happy Coding,
If it helps you or directs U towards the solution,
MARK IT AS ANSWER Nismeh, if this helps please login to Mark As Answer. | Alert Moderator