How to get list of applications in IIS programatically using .Net

In this series of posts I will discuss automation of IIS7 tasks that you usually perform using IIS Management console. Lot of time there are tasks that you want to perform programatically in response to some events that occur in your application. For example based on some rogue actions being performed by a user or group of users, you want to add their IP addresses added to block list or change behavior of application etc. So having an API provides lot of help in those cases.

Microsoft provides a very nice set of managed API that ease development of automation scripts for IIS7 and higher. So these posts are geared towards getting you started with writing automation scripts for IIS on Windows 7 and Windows 2008.

Simple way to get started with this is to create a console application in Visual Studio 2010. You can use earlier version of Visual Studio as well. Since I am using VS2010, I will just refer to that only. You are going to use Microsoft.Web.Administration namespace. You are going to need to add reference to Microsoft.Web.Administration.dll in your project.

Where is Microsoft.Web.Administration.dll

When you bring up Add Reference dialog box in visual studio, you will not see this assembly in list of .Net assembly list. This does not mean that it is not a managed assembly. It is that you will have to browse to this assembly in folders. You can find this assembly in \Windows\System32\inetsrv folder. So browse to it and add the reference in your project.

Get List Of Applications

Just to get started with IIS7 managed api code development, I wrote a simple method that will list of all applications in my IIS. Following code snippet shows how I did it. So this code answers the following question for automation script writers.

  • How to get list of applications in IIS using .Net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Web.Administration;

namespace IISManager
{
 class Program
 {
   static void Main(string[] args)
   {
     GetApplicationAttributes();
   }

   static void GetApplicationAttributes()
   {
      var serverManager = new ServerManager();
      foreach (var site in serverManager.Sites)
      {
        Console.WriteLine("Site: {0}", site.Name);
        foreach (var app in site.Applications)
        {
          Console.WriteLine(app.Path);
        }
      }
   }
 }
}

Pretty simple and straight forward. Path property on Application object is actually the alias that you specified when creating the application in IIS Management Console. IIS uses this alias as path when walking the list of applications. So if you look at the printing text for path you notice a leading \. This shows that the alias is relative path.

Search

Social

Weather

17.6 °C / 63.6 °F

weather conditions Clear

Monthly Posts

Blog Tags