Exception when looping through DirectoryEntries

1k views Asked by At

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)

1

There are 1 answers

0
Claudio Redi On BEST ANSWER

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))