How can I restart a windows serice programatically in .NET? Also, I need to do an operation when the service restart is completed.
+6
A:
Take a look at the ServiceController class.
To perform the operation that needs to be done when the service is restarted, I guess you should do that in the Service yourself (if it is your own service). If you do not have access to the source of the service, then perhaps you can use the WaitForStatus method of the ServiceController.
Frederik Gheysels
2009-09-21 13:29:43
+5
A:
This article uses the ServiceController
class to write methods for Starting, Stopping, and Restarting Windows services; it might be worth taking a look at.
Snippet from the article (the "Restart Service" method):
public static void RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
Donut
2009-09-21 13:32:08
A:
See this article.
Here is a snippet from the article.
//[QUICK CODE] FOR THE IMPATIENT
using System;
using System.Collections.Generic;
using System.Text;
// ADD "using System.ServiceProcess;" after you add the
// Reference to the System.ServiceProcess in the solution Explorer
using System.ServiceProcess;
namespace Using_ServiceController{
class Program{
static void Main(string[] args){
ServiceController myService = new ServiceController();
myService.ServiceName = "ImapiService";
string svcStatus = myService.Status.ToString();
if (svcStatus == "Running"){
myService.Stop();
}else if(svcStatus == "Stopped"){
myService.Start();
}else{
myService.Stop();
}
}
}
}
David Basarab
2009-09-21 13:32:32
+1
A:
How about
var theController = new System.ServiceProcess.ServiceController("IISAdmin");
theController.Stop();
theController.Start();
Don't forget to add the System.ServiceProcess.dll to your project for this to work.
John Nolan
2009-09-21 13:32:40
A:
You could also call the net
command to do this. Example:
System.Diagnostics.Process.Start("net", "stop IISAdmin");
System.Diagnostics.Process.Start("net", "start IISAdmin");
Druid
2009-09-21 13:42:21