I am busy with creating a search function into my GUI application who is running on my Windows Server to add, remove, update and search users. I am almost done building the application, but I can not solve the problem of getting details from an other property which is not given in UserPrincipal like the 'Address' property. How can I get into that property?
I have tried many coding style to get into the given property 'Address', but it still does not work.
Here is the code:
private void ListOfUsers(String ou)
{
List<string> users = new List<string>();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "EMRE", "OU=" + ou + ",dc=emre,dc=han");
UserPrincipal qbeUser = new UserPrincipal(ctx);
PrincipalSearcher search = new PrincipalSearcher(qbeUser);
foreach (UserPrincipal user in search.FindAll())
{
users.Add(user.UserPrincipalName);
users.Add("********");
users.Add(user.GivenName);
users.Add(user.Surname);
if (user.GetUnderlyingObjectType() == typeof(DirectoryEntry))
{
using (var entry = (DirectoryEntry)user.GetUnderlyingObject())
{
if (entry.Properties["Address"] != null)
users.Add(entry.Properties["Street"].Value.ToString());
}
}
users.Add(user.VoiceTelephoneNumber);
users.Add(user.EmailAddress);
users.Add(ou);
}
string[] row = users.ToArray();
var listViewItem = new ListViewItem(row);
lstStudents.Items.Add(listViewItem);
}
I always get a null returned even the property is not null
The attribute you want is actually called streetAddress
. You can also use Properties.Contains
to check if the value exists (although the effect is really the same as checking for null
, just easier to read).
if (entry.Properties.Contains("streetAddress"))
users.Add(entry.Properties["streetAddress"].Value.ToString());
Personally, I like using DirectoryEntry
/DirectorySearcher
directly in general, rather than UserPrincipal
/PrincipalSearcher
because it gives me more control of what it's doing, which can translate into better performance. I wrote a bit about that here: Active Directory: Better performance