1

I use the code snippet below from System.DirectoryServices.AccountManagement to search for user in ActiveDirectory.

The user.Name returns successfully, but how can I retrieve other properties from AD for the user, like msExchRecipientTypeDetails since it is not displayed in VisualStudio 2015 intelligence?

using (PrincipalContext adPrincipalContext = new PrincipalContext(ContextType.Domain, DOMAIN, USERNAME, PASSWORD))
{
    UserPrincipal userPrincipal = new UserPrincipal(adPrincipalContext);                
    userPrincipal.SamAccountName = "user-ID";   
    PrincipalSearcher search = new PrincipalSearcher(userPrincipal);

    foreach (var user in search.FindAll())
    {
        Console.WriteLine("hei " + user.Name);         
        // how to retrive other properties from AD like msExchRecipientTypeDetails??          
    }
}
M. Schena
  • 2,039
  • 1
  • 21
  • 29
Xi Xiao
  • 953
  • 1
  • 12
  • 28

1 Answers1

5

You need to use DirectoryEntry for any custom attributes like that. Add a reference in your project to "System.DirectoryServices" if you haven't already. Since you already have a Principal object, you could do this to get the DirectoryEntry:

var de = user.GetUnderlyingObject();

And because msExchRecipientTypeDetails is a strange AD large integer, you have to jump through hoops to get the real value. Here's a solution from another question to get the value:

var adsLargeInteger = de.Properties["msExchRecipientTypeDetails"].Value;
var highPart = (Int32)adsLargeInteger.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, adsLargeInteger, null);
var lowPart = (Int32)adsLargeInteger.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, adsLargeInteger, null);
if (lowPart < 0) highPart++;
var recipientType = highPart * ((Int64)UInt32.MaxValue + 1) + lowPart;

Update: Three years later I had to look this up again and stumbled across my own answer. But it turns out that sometimes I was getting a negative value when I shouldn't. I found the answer here:

The work-around is to increase the value returned by the HighPart method by one whenever the value returned by the LowPart method is negative.

Therefore, I've added that bit: if (lowPart < 0) highPart++;

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