C# 在Framework 4.5中获取active directory用户属性

C# 在Framework 4.5中获取active directory用户属性,c#,userprincipal,C#,Userprincipal,我有一个从特定组获取用户的代码 PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName); if (grp != null) { foreac

我有一个从特定组获取用户的代码

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
        GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName);

        if (grp != null)
        {
            foreach (Principal p in grp.GetMembers(true))
            {
                Console.WriteLine(p.Name);
            }
        }

问题是,我无法获得用户的手机,家庭电话,部门,国家。有人知道如何使用这种方法吗

尝试在
foreach
循环中声明
UserPrincipal
而不是
Principal
,以允许您使用专门为Active Directory用户定义的属性

或者您可以尝试在循环中包含此代码

Console.WriteLine(p.ExtensionGet("mobile")); // Mobile Phone
Console.WriteLine(p.ExtensionGet("homePhone"));  // Home Phone
Console.WriteLine(p.ExtensionGet("department"));  // Department
Console.WriteLine(p.ExtensionGet("co")); // Country
方法
ExtensionGet
不仅允许您从标准Active Directory字段检索数据,还允许您检索目录中包含的其他自定义数据。

无法直接使用@HuroSwords answer中的方法,因为它是受保护的方法

如上所述,您需要创建自己的子类来使用它。我在下面列出了我过去为获得额外用户属性所做的一个示例

[directoryrndprefix(“CN”)]
[目录对象类(“用户”)]
公共类UserPrincipalExtrade:UserPrincipal
{
公共用户PrincipalContext(PrincipalContext上下文):基本(上下文)
{
}
//实现重载搜索方法FindByIdentity以返回我的扩展类型
公共静态新用户PrincipalContext FindByIdentity(PrincipalContext上下文,字符串标识值)
{
返回(UserPrincipalExtend)FindByIdentityWithType(上下文、typeof(UserPrincipalExtend)、identityValue);
}
//实现重载搜索方法FindByIdentity以返回我的扩展类型
公共静态新用户PrincipalExtend FindByIdentity(PrincipalContext上下文、IdentityType IdentityType、string identityValue)
{
return(userPrincipalExtend)FindByIdentityWithType(上下文、typeof(userPrincipalExtend)、identityType、identityValue);
}
[目录属性(“physicalDeliveryOfficeName”)]
公共弦部
{
得到
{
if(ExtensionGet(“physicalDeliveryOfficeName”).Length!=1)
返回null;
返回(字符串)ExtensionGet(“physicalDeliveryOfficeName”)[0];
}
}
}
然后像使用普通UserPrincipal对象一样使用子类

var domain = new PrincipalContext(ContextType.Domain);
var userPrincipal = UserPrincipalExtended.FindByIdentity(domain, HttpContext.Current.User.Identity.Name);
Console.WriteLine(userPrincipal.Location);

在您的情况下,您可能需要重新获取委托人。

谢谢您的回复,但我没有扩展权限,您是否可以将您的项目定位到.NET 4.5,对吗?在
Principal
class()上有一个
ExtensionGet
方法