【问题标题】:Exception when looping through DirectoryEntries遍历 DirectoryEntries 时出现异常
【发布时间】:2013-09-03 21:19:18
【问题描述】:

以这种方式循环通过 DirectoryEntry 对象时出现异常。我的问题是,我应该在哪里检查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;
            }
        }

例外

索引超出范围。必须为非负数且小于集合的大小。
参数名称:index
在 System.Collections.CollectionBase.System.Collections.IList.get_Item(Int32 索引)

【问题讨论】:

  • 异常清楚地说。 Properties["ServerComment"][0] 导致异常,因为没有元素
  • @marc_s 这不是空指针异常。我需要添加的检查是directoryEntry.Properties["ServerComment"].Count > 0

标签: c# iis directoryentry iis-metabase


【解决方案1】:

看来问题出在这里

directoryEntry.Properties["ServerComment"][0]

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-25
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 2014-05-01
    相关资源
    最近更新 更多