speedreeder speedreeder - 5 months ago 61
C# Question

How can I search Active Directory by username using C#?

I'm trying to search active directory by the username 'admin'. I know for a fact that there is a user with that username in the directory, but the search keeps coming back with nothing.

var attributeName = "userPrincipalName";
var searchString = "admin"
var ent = new DirectoryEntry("LDAP://"dc=corp,dc=contoso,dc=com")
var mySearcher = new DirectorySearcher(ent);
mySearcher.Filter = string.Format("(&(objectClass=user)({0}={1}))", attributeName, searchString);

var userResult = mySearcher.FindOne();

userResult always ends up null. I would love to know why, there must be something that I'm missing.


It turns out that "userPrincipalName" needed to be all lower-case ("userprincipalname"). Good to know, thanks for your responses.