C# 如何按属性(如部门)从Active Directory获取用户列表

C# 如何按属性(如部门)从Active Directory获取用户列表,c#,asp.net,active-directory,C#,Asp.net,Active Directory,我需要提供对Active Directory的搜索使用过滤器,如显示名称,电话和部门。显示姓名和电话很容易,但我被困在部门。这是一个有效的位: using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) { UserPrincipal userPrincipal = new UserPrincipal(context); if (txtDisplayName.Text != "")

我需要提供对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;
但这不起作用。有人知道我怎么做吗

编辑: 我是个白痴,改变了搜索条件,找到了答案。额外的字段称为attibutes

我的扩展用户主体:

[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); }
    }
} 

由于您已经扩展了
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);
           }
        }
    }
}