如何使用C#通过用户名搜索Active Directory?

问题描述:

我正在尝试通过用户名 admin搜索活动目录。我知道一个事实,即目录中有一个使用该用户名的用户,但是搜索一直没有返回。

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总是以null结尾,我很想知道为什么,在那里

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

事实证明, userPrincipalName必须全部为小写( userprincipalname)。很高兴知道,感谢您的回复。

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