我正在使用以下代码访问我的 AD 中的用户列表,但是在我将用户添加到我的组合框的那一行,我得到了空引用异常。
PrincipalContext AD = new PrincipalContext(ContextType.Domain, "mydomainip");
UserPrincipal u = new UserPrincipal(AD);
PrincipalSearcher search = new PrincipalSearcher(u);
foreach (UserPrincipal result in search.FindAll())
{
if (result.DisplayName != null)
{
comboBox2.Items.Add(result.DisplayName);
}
}
知道我做错了什么吗?
我用 Console.WriteLine(result.DisplayName)
替换了组合框,它工作正常。
最佳答案
不能 100% 确定这是否是问题所在 - 但 PrincipalSearcher
确实会返回 Principal
对象的列表。
因此,如果 - 无论出于何种原因 - 您的搜索器将返回 不是 UserPrincipal
的内容,那么您的对象 result
将为 null - 不是它是 .DisplayName
属性。
因此您应该将检查更改为:
foreach (UserPrincipal result in search.FindAll())
{
if (result != null && result.DisplayName != null)
{
comboBox2.Items.Add(result.DisplayName);
}
}
关于c# - 从 Active Directory PrincipalContext 获取所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10665868/