-1

How to get “Company” and “Office” from Active Directory given a UserPrincipal object?

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84
Anuj
  • 1

1 Answers1

0

If you need to read an attribute that the UserPrincipal class does not expose, then you need to use the GetUnderlyingObject() to use the underlying DirectoryEntry object (which is what UserPrincipal uses in the background. This is one reason I don't bother using UserPrincipal at all anymore.

The AD attributes you are looking for are company and physicalDeliveryOfficeName. Assuming you have a UserPrincipal object called user, you would do it like this:

var underlyingObject = (DirectoryEntry) user.GetUnderlyingObject();

var company = underlyingObject.Properties.Contains("company") ?
    (string) underlyingObject.Properties["company"].Value :
    null;

var office = underlyingObject.Properties.Contains("physicalDeliveryOfficeName") ?
    (string) underlyingObject.Properties["physicalDeliveryOfficeName"].Value :
    null;

You use Contains to verify the attribute is in the collection. If the attribute is empty, it won't appear in the Properties collection at all.

Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84