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