如何通过部门等属性从Active Directory获取用户列表

8
我需要使用筛选器在Active Directory上提供搜索,例如显示名称、电话和部门。显示名称和电话很容易,但我在部门上卡住了。以下是有效的部分:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    UserPrincipal userPrincipal = new UserPrincipal(context);

    if (txtDisplayName.Text != "")
        userPrincipal.DisplayName = "*" + txtDisplayName.Text + "*";

    using (PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal))
    {
        foreach (Principal result in searcher.FindAll())
        {
           DirectoryEntry directoryEntry = result.GetUnderlyingObject() as DirectoryEntry;
           DataRow drName = dtProfile.NewRow();
           drName["displayName"] = directoryEntry.Properties["displayName"].Value;
           drName["department"] = directoryEntry.Properties["department"].Value;
           dtProfile.Rows.Add(drName);
        }
    }
} 

我希望我可以添加类似以下内容的东西:

我希望我可以添加类似以下内容的东西:

DirectoryEntry userDirectoryEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry;
if (ddlDepartment.SelectedValue != "")
    userDirectoryEntry.Properties["title"].Value = ddlDepartment.SelectedValue;

但是那样不起作用。有人知道我该怎么做吗?

编辑: 我很蠢,修改了搜索词并找到了答案。额外的字段称为属性。感谢Raymund Macaalay在他的博客文章中介绍如何扩展Principals。

我的扩展UserPrincipal:

[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]

public class UserPrincipalExtended : UserPrincipal
{    
    public UserPrincipalExtended(PrincipalContext context) : base(context) 
    {
    }
    [DirectoryProperty("department")]
    public string department
    {
        get
        {
            if (ExtensionGet("department").Length != 1)
                return null;
            return (string)ExtensionGet("department")[0];
        }
        set { this.ExtensionSet("department", value); }
    }
} 
1个回答

5

既然你已经扩展了UserPrincipal以包含Department属性,那么当你想要搜索时,就需要使用这个扩展的用户主体。

试试这个:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    UserPrincipalExtended userPrincipal = new UserPrincipalExtended(context);

    if (txtDisplayName.Text != "")
    {
        userPrincipal.DisplayName = "*" + txtDisplayName.Text + "*";
    }

    if (!string.IsNullOrEmpty(txtDepartment.Text.Trim())
    {
        userPrincipal.department = txtDepartment.Text.Trim();
    }

    using (PrincipalSearcher searcher = new PrincipalSearcher(userPrincipal))
    {
        foreach (Principal result in searcher.FindAll())
        {
           UserPrincipalExtended upe = result as UserPrincipalExtended;

           if (upe != null)
           {
               DataRow drName = dtProfile.NewRow();
               drName["displayName"] = upe.DisplayName;
               drName["department"] = upe.department;
               dtProfile.Rows.Add(drName);
           }
        }
    }
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接