Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在DirectoryEntries中循环时发生异常_C#_Iis_Directoryentry_Iis Metabase - Fatal编程技术网

C# 在DirectoryEntries中循环时发生异常

C# 在DirectoryEntries中循环时发生异常,c#,iis,directoryentry,iis-metabase,C#,Iis,Directoryentry,Iis Metabase,当以这种方式循环通过DirectoryEntry对象时,我遇到了一个异常。我的问题是,我应该做什么检查来确定站点中是否没有directoryEntries string metabasePath = "IIS://localhost/W3SVC"; DirectoryEntry service = new DirectoryEntry(metabasePath); DirectoryEntries sites = service.Children

当以这种方式循环通过DirectoryEntry对象时,我遇到了一个异常。我的问题是,我应该做什么检查来确定
站点中是否没有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_项(Int32索引)


问题似乎就在这里

directoryEntry.Properties["ServerComment"][0]
如果是这样的话,这些额外的验证就可以了

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

例外清楚地表明<代码>属性[“ServerComment”][0]导致异常,因为没有element@marc_s这不是空指针异常。我需要添加的检查是
directoryEntry.Properties[“ServerComment”].Count>0