1

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
TheFootClan
  • 165
  • 1
  • 3
  • 12
  • You could run the powershell commands from C# to tell the service to stop or start – RyanTimmons91 Jul 07 '17 at 16:36
  • yes, but throws a popup asking to give IIS command prompt access. I was wondering if this method avoids that. I also feel that if I can do it without powershell commands, it would seem cleaner. – TheFootClan Jul 07 '17 at 17:03
  • you do need to have admin access on the box to mess with iis, regardless of how attempt to interact with it. it might be easier to just run your app as an admin and use `appcmd` or `iisreset` commands. – Arian Motamedi Jul 07 '17 at 17:10
  • If you are looking for IIS 7. than could look at this link ! https://stackoverflow.com/a/4959268/4106634 – Binoy Jul 07 '17 at 19:38
  • Running as Administrator worked for me – Andrew Boyd Mar 23 '22 at 00:10

1 Answers1

3

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.

Rohith
  • 5,527
  • 3
  • 27
  • 31