I have console application running from Admin user. I want to restart IIS server using C#. I made this:
public static void Stop()
{
string serviceName = "W3SVC";
var service = GetService(serviceName);
if (service == null) return;
ServiceController sc = new ServiceController(service.ServiceName);
sc.Stop();
}
public static void Start()
{
string serviceName = "W3SVC";
var service = GetService(serviceName);
if (service == null) return;
ServiceController sc = new ServiceController(service.ServiceName);
sc.Start();
}
{
return ServiceController.GetServices()
.Where(x => x.ServiceName == name).FirstOrDefault();
}
The problem that when i stop server, sometimes i get this "visual studio just in time debugger error an unhandled exception", even if my visual studio is not open. I deleted this option from visual studio. But it made me think - am i doing restart right way?
Why starting and stoping my way takes like 5-6 seconds, while if i restart server from iis manager, it restarts for 1 sec.
So what is the correct way to restart server from c# code?