按名字和姓氏搜索用户登录ID

use*_*072 8 c# c#-4.0

我发现如何从活动目录中获取用户列表?

当我只有几个用户时,这很有帮助,但我在AD中有这么多用户,所以当我运行我的查询时

if ((String)(entry.Properties["sn"].Value) == "lname"
     && (String)(entry.Properties["givenName"].Value) == "fname")
{
    return entry.Properties["samAccountName"].Value.ToString();
}
Run Code Online (Sandbox Code Playgroud)

完成花了太长时间.

如何通过名字和姓氏搜索某个特定用户登录ID?

mar*_*c_s 8

由于您使用的是.NET 4,因此应该查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间.在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松查找AD中的用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user - by e.g. his "samAccountName", or the Windows user name or something
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

if(user != null)
{
   // do something here....     
   string samAccountName = user.SamAccountName;
}
Run Code Online (Sandbox Code Playgroud)

如果找不到用户名指定的用户,还可以使用新的搜索功能:

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the first name (GivenName) and a last name (Surname) 
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = firstName;
qbeUser.Surname = lastName;

// 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.....          
}
Run Code Online (Sandbox Code Playgroud)

新的S.DS.AM使得在AD中与用户和群组玩游戏变得非常容易!而找到一个用户也应该相对快速.