搜索活动目录,如果属性为空,则在 c# 中的标签中返回 null 或 “”

本文关键字:标签 返回 null 则在 活动 如果 属性 搜索 | 更新日期: 2023-09-27 17:57:20

我正在尝试搜索活动目录以从中获取用户详细信息。我用标签的详细信息填充标签,如下所示。它工作正常,但如果说用户没有"除法"的值,那么它会弹出以下错误消息。我尝试了不同的东西,但无法让它在标签文本 HELP 中显示 null 或"!

   private void populate_table(string current_user)
    {
        string connection = ConfigurationManager.ConnectionStrings["ADConnection"].ToString();
        DirectorySearcher dssearch = new DirectorySearcher(connection);
        dssearch.Filter = "(sAMAccountName=" + current_user + ")";
        SearchResult sresult = dssearch.FindOne();
        DirectoryEntry dsresult = sresult.GetDirectoryEntry();
        lblfname.Text = dsresult.Properties["givenName"][0].ToString();
        lbllname.Text = dsresult.Properties["sn"][0].ToString();
        lblemail.Text = dsresult.Properties["mail"][0].ToString();
        lblDepartment.Text = dsresult.Properties["department"][0].ToString();
        lblsam.Text = dsresult.Properties["samAccountName"][0].ToString();
        lblBranch.Text = dsresult.Properties["division"][0].ToString();
    }

我得到的错误是

指数超出范围。必须是非负数且小于集合的大小。

搜索活动目录,如果属性为空,则在 c# 中的标签中返回 null 或 “”

您需要检查是否设置了给定的属性:

if (dsresult.Properties["division"] != null &&
    dsresult.Properties["division"].Count > 0)
{ 
    lblBranch.Text = dsresult.Properties["division"][0].ToString();
}
else     
{ 
    lblBranch.Text = string.Empty;
}

这就是 AD 的工作方式 - 您基本上需要对任何不是必需属性的属性进行检查。任何不可为空的内容都可以在AD中"未设置",因此.Properties["...."]将被null