I need to be able to Start/Stop the IIS in C#. I've been tasked with creating this module by my manager. The following is my attempt:
ServiceController service = new ServiceController("w3svc");
service.Stop();
I am getting the following exception:
Cannot open w3svc service on computer '.'.
I am writing the code to stop the IIS on the local machine.
I also tried IISAdmin
as the servicename, but IISAdmin
could not be found on my computer.
You have to work with Microsoft.Web.Administration .
The Microsoft.Web.Administration (MWA) APIs are built as a managed
code wrapper over the Application Host Administration API (AHADMIN)
which is a native code interface library. It provides a programmatic
way to access and update the web server configuration and
administration information.
using System;
using System.Linq;
using Microsoft.Web.Administration;
class Program
{
static void Main(string[] args)
{
var server = new ServerManager();
var site = server.Sites.FirstOrDefault(s => s.Name == "Default Web Site");
if (site != null)
{
//stop the site
site.Stop();
//start the site
site.Start();
}
}
}
This article discuss detailed scenarios for using Microsoft.Web.Administration.
Please note that you have to run your C# application as Administrator to do anything on IIS.Otherwise you may get Access denied.