C#LDAP查询以检索组织单位中的所有用户

时间:2011-10-11 05:22:17

标签: c# ldap

我正在尝试运行一个LDAP查询,该查询将返回属于组织单位OU=EmployeesOU=FormerEmployees的所有用户,但我无法到达任何地方。

我尝试使用distinguishedName进行搜索,但似乎不支持通配符。我知道必须有一个更简单的方法,但我的搜索努力没有产生任何结果

1 个答案:

答案 0 :(得分:10)

如果您使用的是.NET 3.5及更高版本,则可以使用PrincipalSearcher和“按示例查询”主体进行搜索:

// create your domain context and define what container to search in - here OU=Employees
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=Employees,DC=YourCompany,DC=com");

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// that is still active
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.Enabled = true;

// 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

中的新功能

如果您更喜欢“旧的”.NET 2.0样式,则需要创建一个与要枚举对象的OU对应的基础DirectoryEntry,然后需要创建{{1}搜索对象 - 就像这样:

DirectorySearcher
相关问题