繁体   English   中英

循环遍历DirectoryEntries时出现异常

[英]Exception when looping through DirectoryEntries

我以这种方式循环遍历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;
            }
        }

例外

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

似乎问题出在这里

directoryEntry.Properties["ServerComment"][0]

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM