从Active Directory PrincipalContext获取所有用户 [英] Getting all users from Active Directory PrincipalContext

查看:136
本文介绍了从Active Directory PrincipalContext获取所有用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码访问广告中的用户列表,但是在将用户添加到组合框的那一行上,我得到了空引用异常。

I am using the following code to access the list of users in my AD, however on the line where I add the users to my combobox I get a null reference exception.

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);
    }
}

任何人都知道我在做什么错吗?

Any idea what I'm doing wrong?

我用 Console.WriteLine(result.DisplayName)替换了组合框,并且效果很好。

I replaced the combobox with a Console.WriteLine(result.DisplayName) and it works fine.

推荐答案

不是100%不确定这是否是问题-但是 PrincipalSearcher 确实返回了 Principal 对象。

Not 100% sure if that's the problem - but PrincipalSearcher really returns a list of Principal objects.

因此,如果-由于某种原因-搜索者返回的内容不是 UserPrincipal ,那么您的对象结果将为空-不是 .DisplayName 属性。

So if - for whatever reason - your searcher would return something that's not a UserPrincipal, then your object result would be null - not it's .DisplayName property.

因此,您应该将支票更改为:

So you should change your checking to:

foreach (UserPrincipal result in search.FindAll())
{
    if (result != null && result.DisplayName != null)
    {
        comboBox2.Items.Add(result.DisplayName);
    }
}

这篇关于从Active Directory PrincipalContext获取所有用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆