我需要使用显示名称、电话和部门等过滤器在 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 的博客文章。
我的扩展用户主体:
[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); }
}
}