c# – 搜索特定OU Active Directory中的用户

我的Active Directory中有不同的OU用于不同的用户,我想使用C#获取特定OU的所有用户.

目前我有这个过滤器,但它返回所有OU的所有用户

(&(objectClass=User)(objectCategory=Person))

请帮助我使用ldap查找特定用户的用户

解决方法:

您可以使用PrincipalSearcher和“按示例查询”主体进行搜索:

// LDAP string to define your OU
string ou = "OU=Sales,DC=YourCompany,DC=com";

// set up a "PrincipalContext" for that OU
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Yourcompany.com", ou))
{
    // define the "query-by-example" user (or group, or computer) for your search
    UserPrincipal qbeUser = new UserPrincipal(ctx);

    // set whatever attributes you want to limit your search for, e.g. Name, etc.
    qbeUser.Surname = "Smith";

    // define a searcher for that context and that query-by-example 
    using (PrincipalSearcher searcher = new PrincipalSearcher(qbeUser))
    {
        foreach (Principal p in searcher.FindAll())
        {
            // Convert the "generic" Principal to a UserPrincipal
            UserPrincipal user = p as UserPrincipal;

            if (user != null)
            {
                // do something with your found user....
            }
        }
    }

如果你还没有 – 绝对阅读MSDN文章Managing Directory Security Principals in the .NET Framework 3.5,它很好地展示了如何充分利用System.DirectoryServices.AccountManagement中的新功能.或者查看MSDN documentation on the System.DirectoryServices.AccountManagement命名空间.

当然,根据您的需要,您可能希望在您创建的“按示例查询”用户主体上指定其他属性:

> DisplayName(通常:名字空间姓氏)
> SAM帐户名称 – 您的Windows / AD帐户名称
>用户主体名称 – 您的“username@yourcompany.com”样式名称

您可以在UserPrincipal上指定任何属性,并将这些属性用作PrincipalSearcher的“按示例查询”.

上一篇:丑数


下一篇:域用户登录桌面自动映射个人文件夹