Start and Stop IIS on remote machine through C# code

Quest picture Quest · Jul 24, 2013 · Viewed 11k times · Source

I need to stop IIS on a remote machine and then do some work and then start the IIS service again once the work is done. I am trying to do this using C# code. I have seen some similar questions about starting IIS on remote machines through code. But I have not been able to get any working solution from it. Some clearcut C# code about how to do the start and stop operations would be really helpful.

Answer

Mark picture Mark · Jul 24, 2013

The Microsoft.Web.Administration Namespace has what you need for administering IIS. Check it out at: http://msdn.microsoft.com/en-us/library/microsoft.web.administration%28VS.90%29.aspx.

However if you just want to stop and start services you can manage your services using the Service.Controller

 ServiceController service = new ServiceController(serviceName);
 TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
 service.Start();
 service.WaitForStatus(ServiceControllerStatus.Running, timeout);

The Service.Controller class page should have all the information you require. Find it at, http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx

Here's a complete example you can use to start a service:

public static void StartService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
  catch
  {
    // ...
  }
}

Review the link above for more documentation.

You can connect to a remote server as follows:

ServiceController svc =  new ServiceController("Service", "COMPUTERNAME");

If you require a different set of permissions on the remote server there's a lot more work involved. See this question, Starting remote Windows services with ServiceController and impersonation.