如果你想使用旧式的DirectorySearcher,那么技巧就是绑定到你想列出用户的OU,例如。你的部门:
var searchRoot = new DirectoryEntry("LDAP://OU=YourDepartment,DC=au,DC=company,DC=com");
var search = new DirectorySearcher(searchRoot);
然后做一个
search.FindAll();
并迭代结果。
另一种选择是使用较新的 System.DirectoryServices.AccountManagement 命名空间并使用它的强类型、易于使用的类,例如 PrincipalSearcher 和“按示例查询”主体来进行搜索:
// create your domain context and define a "starting" container where to search in
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=YourDepartment,DC=au,DC=company,DC=com"))
{
// define a "query-by-example" principal - here, we search for a UserPrincipal
// and with the first name (GivenName) of "Bruce" and a last name (Surname) of "Miller"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.GivenName = "Bruce";
qbeUser.Surname = "Miller";
// 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.....
}
}
如果您还没有 - 一定要阅读 MSDN 文章 Managing Directory Security Principals in the .NET Framework 3.5,它很好地展示了如何充分利用 System.DirectoryServices.AccountManagement 中的新功能。或查看MSDN documentation on the System.DirectoryServices.AccountManagement 命名空间。
当然,根据您的需要,您可能希望在您创建的“示例查询”用户主体上指定其他属性:
-
DisplayName(通常:名字 + 空格 + 姓氏)
-
SAM Account Name - 您的 Windows/AD 帐户名
-
User Principal Name - 您的“username@yourcompany.com”样式名称
您可以在UserPrincipal 上指定任何属性并将其用作PrincipalSearcher 的“示例查询”。
更新:要获取组的成员,请使用以下代码:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
// if found....
if (group != null)
{
// iterate over members
foreach (Principal p in group.GetMembers())
{
Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
// do whatever you need to do to those members
}
}
}