c# - 搜索 Active Directory 并在 C# 中的标签中返回 null 或 ""(如果属性为空)

标签 c# asp.net .net active-directory ldap

我正在尝试搜索事件目录以从中获取用户详细信息。我用标签的详细信息填充标签,如下所示。它工作正常,但如果说用户没有“除法”的值,那么它会弹出以下错误消息。我尝试了不同的方法,但无法让它在标签文本帮助中显示 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();
    }

我得到的错误是

Index was out of range. Must be non-negative and less than the size of the collection.

最佳答案

您需要检查以查看给定属性是否已设置:

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

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

关于c# - 搜索 Active Directory 并在 C# 中的标签中返回 null 或 ""(如果属性为空),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22909384/

相关文章:

c# - 如何以编程方式在 Outlook 邮件正文中创建表格

c# - 自动调整固定大小标签中的文本以避免文本跳到第二行

asp.net - 获取项目的深度

.net - COM 互操作是否可能受到 Visual Studio 托管进程的影响?

c# - 使单选按钮默认选中并使文本框无法在 C# 中输入

c# - Cookie.ExpireTimeSpan 被忽略并在 CookieAuthentication 中设置为 Session

C# 正则表达式仅删除元素名称中的字符,而不替换值

asp.net - 在asp.net c#中使用 session 进行用户身份验证

c# - 如何防止在文本框上按 Enter 键时重定向到另一个 aspx 页面?

c# - 用C#在MySQL中执行带参数的存储过程?