ASPX C#在Active Directory中搜索用户

时间:2013-12-13 20:14:12

标签: c# active-directory

是否有人知道使用DirectoryServices在Active Directory中搜索单个用户的最佳方式?我的代码目前列出了给定LDAP路径下的所有子'OU',但我现在想要在路径下添加搜索用户的功能。代码是否可以适应搜索用户?

我已经包含了列出当前OU中所有用户的代码:

DirectoryEntry Ldap = new DirectoryEntry("LDAP://" + ouselect.SelectedValue + ";" + LDAPRoot, LDAPUser, LDAPPass);
DirectorySearcher ad_search = new DirectorySearcher(Ldap);

ad_search.Filter = "(objectClass=User)";
ad_search.SearchScope = SearchScope.Subtree;
ad_search.PropertiesToLoad.Add("samaccountname");  

任何人都可以提供的任何指针都非常棒。

2 个答案:

答案 0 :(得分:2)

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

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

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // do something here....     
    }
}

新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!

PS:PrincipalContext为其构造函数提供了许多不同的重载 - 您还可以定义用于查询Active Directory的用户名/密码,如果需要,还可以定义“起始”容器至。 Check out the MSDN documentation for details on this

答案 1 :(得分:0)

你的代码几乎就在那里。只需更改过滤器即可搜索特定的AD属性,而不是所有用户。

ad_search.Filter = string.Format("(department={0})", department);

ad_search.Filter = string.Format("(displayName={0})", "James Doe");

ad_search.Filter = string.Format("(sAMAccountName={0})", "some.username");

相关问题