views:

231

answers:

3

Hi,

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

+1  A: 

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);
        }
    }
Darin Dimitrov
Same problem. I have a test aspx page using the code you gave me, except with Response.Write instead of Console.WriteLine, and it prints out 11 numbers. Our IIS currently now has 17 websites, not 11. Where are the missing 6?
mellamokb
+1  A: 

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 />");
}
mellamokb
A: 

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.

RickNZ