8
我需要使用過濾器(如顯示名稱,電話和部門)在Active Directory上提供搜索。顯示名稱和電話很容易,但我被困在部門。這是一個工作位:如何通過屬性(例如部門)從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。 Thanks Raymund Macaalay for your blog article on extending 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); }
}
}