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?
Try to use this code to restart IIS.
using System.ServiceProcess;
using (ServiceController controller = new ServiceController())
{
controller.MachineName = “My local or remote computer name”;
controller.ServiceName = “IIS Service Name”; // i.e “w3svc”
if (controller.Status != ServiceControllerStatus.Running)
{
// Start the service
controller.Start();
Log.Debug(“IIS has been started successfully, now checking again for
webservice availability”);
}
else
{
// Stop the service
controller.Stop();
// Start the service
controller.Start();
Log.Debug(“IIS has been restarted successfully”);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.