Исключение при цикле через DirectoryEntries
Я получаю исключение при циклическом перемещении объектов DirectoryEntry таким способом. Мой вопрос: какую проверку я должен сделать, чтобы определить, нет ли в каталоге DirectoryEntries 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;
}
}
исключение
Индекс был вне диапазона. Должен быть неотрицательным и меньшим, чем размер коллекции.
Имя параметра: индекс
в System.Collections.CollectionBase.System.Collections.IList.get_Item(Int32 index)
1 ответ
Решение
Кажется, проблема здесь
directoryEntry.Properties["ServerComment"][0]
Если это так, то эти дополнительные проверки должны помочь
if (directoryEntry.Properties["ServerComment"] != null &&
directoryEntry.Properties["ServerComment"].Count > 0 &&
directoryEntry.Properties["ServerComment"][0].Equals(SiteName))