如果您想使用 old-style 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,它很好地展示了如何充分利用 .NET Framework 中的新功能System.DirectoryServices.AccountManagement
。或查看System.DirectoryServices.AccountManagement命名空间上的 MSDN 文档。
当然,根据您的需要,您可能希望在您创建的“示例查询”用户主体上指定其他属性:
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
}
}
}