Can I get the User Department from Active Directory using PrincipalContext()

Viewed 4199

I am trying to get the user's department from Active Directory. I have the following class:

public class DomainContext
{
        public string DisplayName { get; set; }
        public string Name { get; set; }
        public string SamAccountName { get; set; }
        public string DistinguishedName { get; set; }
        public string UserPrincipalName { get; set; }
        public string Department { get; set; }
}

Then using the below method, I am able to get the user name, display name, sam account, etc....

public override void getUserDepts(SPItemEventProperties properties)
{
    base.ItemUpdating(properties);

    string[] offices = new string[] { "OfficeA", "OfficeB", "OfficeC" };

    string ADServerName = "*****";
    string ADusername = "******";
    string ADpassword = "*****";

    using (var context = new PrincipalContext(ContextType.Domain, ADServerName, ADusername, ADpassword))
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        var searchResults = searcher.FindAll();

        foreach (Principal p in searchResults)
        {
            if (p.DistinguishedName.ToLower().Contains(offices[0].ToLower()) || p.DistinguishedName.ToLower().Contains(offices[1].ToLower()) || p.DistinguishedName.ToLower().Contains(offices[2].ToLower())))
            {
                DomainContext dc = new DomainContext();
                dc.DisplayName = p.DisplayName;
                dc.UserPrincipalName = p.UserPrincipalName;
                dc.Name = p.Name;
                dc.SamAccountName = p.SamAccountName;
                dc.DistinguishedName = p.DistinguishedName;
                // dc.Department = p. **CAN NOT GET THE DEPARTMENT NAME**
            }
        }
    }
}

but I am unable to locate how I can get the department name.

1 Answers
Related