Recursively List Virtual Directories in IIS with C# and DirectoryServices

You’ve probably seen a lot of VBScript scripts that manage IIS via ADSI objects, but let’s say you want to write something in .NET. Maybe C#? Maybe compiled code, with a UI?

Enter DirectoryServices, a .NET-friendly wrapper for ADSI (Active Directory Services Interface). IIS (along with LDAP and WinNT) is known as an ADSI Provider, meaning it supports the ADSI interface, enabling you to work with files, directories, etc. So your .NET application can use DirectoryServices to create, delete, and enumerate IIS directories and virtual directories, like this:

Your .NET Application <-> DirectoryServices <-> ADSI <-> IIS

Below is a simple code snippet that will list out all virtual directories in an IIS web site. It’s different than other scripts I’ve seen in that it will list virtual directories below the root.

// call the function once to kick it off

WriteVDirs("localhost", 1, "");

// function that recursively walks through IIS dir & vdirs & lists all the virtual directories
public void WriteVDirs(string serverName, int SiteNumber, string path)
{
DirectoryEntry de =
new DirectoryEntry("IIS://" + serverName + "/W3SVC/" +
SiteNumber.ToString() + "/Root" + path);
DirectoryEntries dirs;
try {
dirs = de.Children;
foreach(DirectoryEntry d in dirs) {
if (0 == String.Compare( d.SchemaClassName, "IIsWebDirectory")) {
string fullPath = path + "/" + d.Name;
WriteVDirs(serverName, SiteNumber, fullPath);
}
else if (0 == String.Compare( d.SchemaClassName, "IIsWebVirtualDir")) {
string fullPath = path + "/" + d.Name;
Console.WriteLine(fullPath + ":" + d.Properties["Path"].Value);
WriteVDirs(serverName, SiteNumber, fullPath);
}
}
}
catch (Exception ex) {
Console.WriteLine("ERROR: " + ex.Message);
}
}

By default the code runs under the credentials of the account running the application, but you can specify a different account using the DirectoryEntry.Username & DirectoryEntry.Password properties, e.g.

  DirectoryEntry de = new DirectoryEntry("IIS://localhost/W3SVC/1");

de.Username = "MYDOMAIN/Username";
de.Password = "password";

Lastly, note that in order to use System.DirectoryServices in your C# project, you’ll need to deliberately add a reference to the .NET System.DirectoryServices.dll.

You can research the classes more on MSDN.

0