繁体   English   中英

如何通过诸如Department之类的属性从Active Directory获取用户列表

[英]How to get list of Users from Active Directory by attributes such as Department

我需要使用显示名称,电话和部门等过滤器在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。 感谢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); }
    }
} 

由于已经将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);
           }
        }
    }
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM