您不需要枚举所有用户来查找其中一个用户!试试这段代码:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname")) { UserPrincipal yourUser = UserPrincipal.FindByIdentity(context, EmailAddress); if (yourUser != null) { user.FirstName = result.GivenName; user.LastName = result.Surname; } }
如果这不起作用,或者您需要一次搜索多个条件,则使用PrincipalSearcher
QBE(按示例查询)方法 - 搜索您需要的一个用户 - 不要遍历所有用户!
// create your domain context using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname")) { // define a "query-by-example" principal - UserPrincipal qbeUser = new UserPrincipal(ctx); qbeUser.EmailAddress = yourEmailAddress; // create your principal searcher passing in the QBE principal PrincipalSearcher srch = new PrincipalSearcher(qbeUser); // find all matches foreach(var found in srch.FindAll()) { // do whatever here - "found" is of type "Principal" - it could be user, group, computer..... } }