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.
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.
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