user541597
user541597

Reputation: 4355

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.

Upvotes: 11

Views: 22870

Answers (1)

marc_s
marc_s

Reputation: 755471

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

Upvotes: 10

Related Questions