Question

I use code like the following in ASP.Net to enumerate the websites in IIS:

string metabasePath = "IIS://localhost/W3SVC";
DirectoryEntry service = new DirectoryEntry(metabasePath);

service.RefreshCache();
string className = service.SchemaClassName.ToString();

if (className.EndsWith("Service"))
{
    DirectoryEntries sites = service.Children;
    foreach (DirectoryEntry site in sites)
    {
        ProcessSite(site);
    }
}

However, I find that only the first 11 sites out of 16 sites are ever processed. I have fought with this for a few hours, and cannot find any way to get past the first 11 sites in IIS. I've tried searching recursively, I've tried using the DirectorySearcher to no avail, I've tried enumerating multiple times or using some sort of a filter without any luck.

Any ideas?

Thanks!

~ mellamokb

Was it helpful?

Solution

I have decided to use WMI instead of DirectoryServices, which seems to work perfectly:

ManagementScope oms = new ManagementScope(@"\\.\root\MicrosoftIISv2");
oms.Connect();

ObjectQuery oQuery = new ObjectQuery("select * from IISWebServerSetting");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oms, oQuery);
foreach (ManagementObject oreturn in oSearcher.Get())
{
    Response.Write(oreturn["ServerComment"] + " (" + oreturn["Name"] + ")<br />");
}

OTHER TIPS

To enumerate all sites on the local server you may try this:

class Program
{
    static void Main(string[] args)
    {
        var iis = new DirectoryEntry("IIS://localhost/W3SVC");
        var sites = (from DirectoryEntry entry in iis.Children
                     where entry.SchemaClassName == "IIsWebServer"
                     select entry).ToArray();

        foreach (var site in sites)
        {
            Console.WriteLine(site.Name);
        }
    }

Are you by chance running IIS 7? If so, that might explain the problem, since the metabase exists only for compatibility reasons; it is no longer the primary store.

You would probably need to parse applicationHost.config instead -- though WMI is a good option, too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top