Here are two helper functions to add onto Garetts answer. With these, you can loop through each domain and get all its virtual directories, including ones that are not in the domains root folder.
Get Site ID from domain name:
string GetSiteID(string domain)
{
string siteId = string.Empty;
DirectoryEntry iis = new DirectoryEntry("IIS://localhost/W3SVC");
foreach (DirectoryEntry entry in iis.Children)
if (entry.SchemaClassName.ToLower() == "iiswebserver")
if (entry.Properties["ServerComment"].Value.ToString().ToLower() == domain.ToLower())
siteId = entry.Name;
if (string.IsNullOrEmpty(siteId))
throw new Exception("Could not find site '" + domain + "'");
return siteId;
}
Get all descendant entries (recursively) for site entry
static DirectoryEntry[] GetAllChildren(DirectoryEntry entry)
{
List<DirectoryEntry> children = new List<DirectoryEntry>();
foreach (DirectoryEntry child in entry.Children)
{
children.Add(child);
children.AddRange(GetAllChildren(child));
}
return children.ToArray();
}
Mapping Site ID's for large number of sites
Edit: After testing this with a server containing several hundred domains, GetSiteID() performs very slow because it is enumerating all the sites again and again to get the id. The below function enumerates the sites only a single time and maps each one to its id and stores it in a dictionary. Then when you need the site id you pull it from the dictionary instead, Sites["domain"]. If you are looking up virtual directories for all sites on a server, or a large amount, the below will be much faster than GetSiteID() above.
public static Dictionary<string, string> MapSiteIDs()
{
DirectoryEntry IIS = new DirectoryEntry("IIS://localhost/W3SVC");
Dictionary<string, string> dictionary = new Dictionary<string, string>(); // key=domain, value=siteId
foreach (DirectoryEntry entry in IIS.Children)
{
if (entry.SchemaClassName.ToLower() == "iiswebserver")
{
string domainName = entry.Properties["ServerComment"].Value.ToString().ToLower();
string siteID = entry.Name;
dictionary.Add(domainName, siteID);
}
}
return dictionary;
}