"Properties" 和 "GetProperties" 对 UserPrincipal 不可用,无法获取 'Department' 和其他值

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

我正在尝试获取 AD 用户的 'Departmment' 值,我有一个 UserPrincipal 对象,我使用以下方法获取它。

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;
    }

但是当我尝试使用任一方法获取 'Department' 值时...

domainUser.GetProperty("department");

domainUser.Properties["department"].Value;

我收到错误“'UserPrincipal' 不包含“GetProperty”或“Properties”的定义。

我发现 'Department' 在 UserPrincipal 中的基础对象的属性中,所以我尝试...

domainUser.GetUnderlyingObject();

获取底层对象,调试时我可以在它的属性中看到'Department',但是没有访问属性的功能(至少没有我的.net Core 3.1版本似乎想要的功能让我用)。

这获取给定 AD 字符串的值 属性:

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;
}

示例:

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