Start and Stop IIS on remote machine through C# code [closed]

青春壹個敷衍的年華 提交于 2019-12-09 23:41:34

问题


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.


回答1:


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.




回答2:


Solution A:

You can create a .bat file runtime like:

# for stopping
iisreset -stop

# for starting
iisreset -start

Then execute it on the remote machine using PsExec.

Solution B: Start or stop the "IISADMIN" Service directly. To manage remote services you can use below links:

  • Monitor and Manage Services on Remote Machines
  • Using the ServiceController in C# to stop and start a service

Be lucky ;)



来源:https://stackoverflow.com/questions/17831477/start-and-stop-iis-on-remote-machine-through-c-sharp-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!