Website Design Chester by the Informatics Centre

Querying IIS through C#

As part of our yearly network upgrades we enhance the functionality of the student webserver - the development environment that undergraduates, postgraduates and PhD students use to host their web work whilst studying at the University of Chester. This year we're adding the ability to create IIS Applications, Virtual Directories and Configure SSL through a web interface, rather than having to use the actual IIS Manager GUI tool. To facilitate this we are going to install the Microsoft.Web.Administration library and use the relatively new ServerManager class which allows us to programmatically interact with the IIS configuration metadata.

To install the library you can use the package manager console to get it from NuGet;


Install-Package Microsoft.Web.Administration

With that installed we can now use the ServerManager class to interact with the server;


using Microsoft.Web.Administration;



using (ServerManager serverManager = new ServerManager())

    Site site = serverManager.Sites("Site One");

}

The above code creates a connection to the local IIS Server and sets a Site object with a website called "Site One". We can then get a list of all Applications hosted within Site One and add them to a List.


List<string> applications = new List<string>();



foreach (Application application in site.Applications)

{

    applications.Add(application.Path);

}

We can also get a list of all Virtual Directories in the website and add them to a List.


List<string> virtualDirectories = new List<string>();



foreach (Application application in site.Applications)

{

    foreach (VirtualDirectory virtualDirectory in application.VirtualDirectories)

    {

        virtualDirectories.Add(virtualDirectory.Path);

    }

}

In a future post we will discuss how we can use the same code to create new / delete existing Virtual Directories and Applications. The ServerManager class provides the same functionality as the Graphical / PowerShell interfaces for IIS which makes it ideal for web-based management of your infrastructure.

View all Informatics Centre blog posts.