我使用以下代码来访问 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
对象。
因此,如果 - 无论出于何种原因 - 你的搜索者会返回一些东西not a UserPrincipal
,那么你的对象result
将为 null - 不是.DisplayName
财产。
所以你应该将检查更改为:
foreach (UserPrincipal result in search.FindAll())
{
if (result != null && result.DisplayName != null)
{
comboBox2.Items.Add(result.DisplayName);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)