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

标签 c# ldap

我正在尝试运行 LDAP 查询,该查询将返回属于组织单位 OU=EmployeesOU=FormerEmployees 的所有用户,但我一无所获.

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

最佳答案

如果您使用的是 .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 风格,则需要创建一个基础 DirectoryEntry对应于您要在其中枚举对象的 OU,然后您需要创建一个 DirectorySearcher搜索对象 - 像这样:

// create your "base" - the OU "FormerEmployees"
DirectoryEntry formerEmployeeOU = new DirectoryEntry("LDAP://OU=FormerEmployees,DC=YourCompany,DC=com");

// create a searcher to find objects inside this container
DirectorySearcher feSearcher = new DirectorySearcher(formerEmployeeOU);

// define a standard LDAP filter for what you search for - here "users"    
feSearcher.Filter = "(objectCategory=user)";

// define the properties you want to have returned by the searcher
feSearcher.PropertiesToLoad.Add("distinguishedName");
feSearcher.PropertiesToLoad.Add("sn");
feSearcher.PropertiesToLoad.Add("givenName");
feSearcher.PropertiesToLoad.Add("mail");

// search and iterate over results
foreach (SearchResult sr in feSearcher.FindAll())
{
    // for each property, you need to check where it's present in sr.Properties
    if (sr.Properties["description"] != null && sr.Properties["description"].Count > 0)
    {
       string description = sr.Properties["description"][0].ToString();
    }
}

关于C# LDAP 查询以检索组织单位中的所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7721696/

相关文章:

windows - LDAP 与 Windows AD 的绑定(bind)失败并显示 80090308 : LdapErr: DSID-0C0903AA

azure - 是否可以使用 LDAP 从 Office365 - Exchange Online/Azure 检索数据?

c# - ClickOnce CheckForUpdate() 一段时间后返回 null

c# - Discord.net 1.0 - 如何获取要删除的消息?

c# - ASP.NET:获取TreeNode的容器TreeView

c# - 从哈希集中替换并合并 "Duplicates"

java - 在 Apache Camel LDAP 组件中对结果进行分页

c# - 'field' 但像 'type' 一样使用

active-directory - .net5 MVC6 应用程序上的 Active Directory/LDAP

java - 如何使用 SSL 连接到 ApacheDS?