Question

I am getting an exception when looping through DirectoryEntry objects in this fashion. My question is, what check should I do where to determine if there are no directoryEntries in sites?

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

        DirectoryEntries sites = service.Children;

        bool siteExists = false;
        foreach (DirectoryEntry directoryEntry in sites)
        {
            if (directoryEntry.Properties["ServerComment"][0].Equals(SiteName)) //exception thrown here
            {
                siteExists = true;
                break;
            }
        }

Exception

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.CollectionBase.System.Collections.IList.get_Item(Int32 index)

Was it helpful?

Solution

It seems that the problem is here

directoryEntry.Properties["ServerComment"][0]

If this is the case, these extra validations should do the trick

if (directoryEntry.Properties["ServerComment"] != null &&
    directoryEntry.Properties["ServerComment"].Count > 0 &&
    directoryEntry.Properties["ServerComment"][0].Equals(SiteName))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top