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)
It seems that the problem is here
If this is the case, these extra validations should do the trick