How to get a list of users from Active Directory by attributes such as Department

I need to provide an Active Directory search using filters such as Display name, Telephone and Department. Displaying the name and phone number is easy, but I'm stuck in the ward. This is the bit that works:

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

I was hoping I could just add something like:

 DirectoryEntry userDirectoryEntry = userPrincipal.GetUnderlyingObject() as DirectoryEntry; if (ddlDepartment.SelectedValue != "") userDirectoryEntry.Properties["title"].Value = ddlDepartment.SelectedValue; 

But that does not work. Does anyone know how I can do this?

Edit: I am an idiot, changed my search query and found an answer. Additional fields are called attributes. Thanks to Raymund Macaalay for your renewal blog article .

My advanced 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); } } } 
+8
c # active-directory
source share
1 answer

Since you have already extended UserPrincipal to include the Department attribute, you will need to use this extended version of the user principal if you want to perform a search.

Try the following:

 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); } } } } 
+5
source share

All Articles