简体   繁体   中英

Getting all users from 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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM