Search code examples
c#active-directory.net-core-3.1directoryservicesuserprincipal

"Properties" and "GetProperties" not available for UserPrincipal, unable to get 'Department' and other values


I'm trying to get the 'Departmment' value for AD Users, I have a UserPrincipal object, which I get using the following.

public ADUser getADUser(string sid)
    {
        ADUser ADUser = new ADUser();

        string container = "OU=Users,OU=comp,DC=domain,DC=domaindomain";
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain", container))
        {
            UserPrincipal userPrinciple = new UserPrincipal(ctx) { Enabled = true };
            PrincipalSearcher principalSearcher = new PrincipalSearcher(userPrinciple);
            ((DirectorySearcher)principalSearcher.GetUnderlyingSearcher()).SearchScope = SearchScope.OneLevel;

            UserPrincipal domainUser = UserPrincipal.FindByIdentity(ctx,IdentityType.Sid, (sid));                

            ADUser = new ADUser()
            {
                SID = domainUser.Sid.ToString(),
                GUID = domainUser.Guid.ToString(),
                Description = domainUser.Description,
                DisplayName = domainUser.DisplayName,
                EmailAddress = domainUser.EmailAddress,
                VoiceTelephoneNumber = domainUser.VoiceTelephoneNumber,
                Enabled = domainUser.Enabled,
                permissions = getADUserPermissions(sid)
            };
               
        } //using

        return ADUser;
    }

But when I try to get the 'Department' value using either...

domainUser.GetProperty("department");

or

domainUser.Properties["department"].Value;

I get the error that "'UserPrincipal' does not contain a definition for either "GetProperty" or "Properties".

I've found that 'Department' is in the properties of the underlying object in the UserPrincipal, so I tried...

domainUser.GetUnderlyingObject();

Which gets the underlying object, and when debugging I can see 'Department' in its properties, but theres no function to access the properties (at least no function that my version of .net Core 3.1 seems to want to let me use).


Solution

  • This gets the value of a given AD string property:

    private string GetAdPropertyValue(DirectoryEntry userAccount, string adPropertyKey)
    {
        string result = null;
        PropertyValueCollection property = userAccount.Properties[adPropertyKey];
    
        if (property != null)
        {
            object propertyValue = property.Value;
    
            if (propertyValue != null)
            {
                string propertyValueString = (string)propertyValue;
                result = propertyValueString.Trim();
            }
        }
    
        return result;
    }
    

    Example:

    DirectoryEntry directoryEntryUser = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
    string departmentName = GetAdPropertyValue(directoryEntryUser, "department");