Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 675
user541597 Avatar asked May 19 '12 14:05

user541597


1 Answers

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);
    }
}
like image 91
marc_s Avatar answered Sep 17 '22 18:09

marc_s