簡體   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