循环遍历DirectoryEntries时出现异常

时间:2013-09-03 21:19:18

标签: c# iis directoryentry iis-metabase

以这种方式循环遍历DirectoryEntry对象时出现异常。我的问题是,我应该在哪里检查确定sites中是否没有directoryEntries?

        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 个答案:

答案 0 :(得分:2)

似乎问题就在这里

directoryEntry.Properties["ServerComment"][0]

如果是这种情况,这些额外的验证应该可以解决问题

if (directoryEntry.Properties["ServerComment"] != null &&
    directoryEntry.Properties["ServerComment"].Count > 0 &&
    directoryEntry.Properties["ServerComment"][0].Equals(SiteName))