从Active Directory获取用户姓名

16

我需要从Active Directory中仅显示用户的名称,我正在使用

 lbl_Login.Text = User.Identity.Name; //the result is domain\username

这显示了用户的名称,但不是用户的真实姓名,我查看了其他相关的问题和答案,但没有得到解决方案。

是否有类似于“User.Identity.Name”的属性仅获取用户的名称?


我将发布一种简单的方法来获取完整的显示名称。 - MethodMan
2个回答

28

您想要从活动目录中获取用户的名称。可以尝试以下代码:

string name ="";
using (var context = new PrincipalContext(ContextType.Domain))
{
    var usr = UserPrincipal.FindByIdentity(context, User.Identity.Name); 
    if (usr != null)
       name = usr.DisplayName;  
}

或者可以参考来自social.msdn.microsoft.com的内容:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.Current;
string displayName = user.DisplayName;

或者是这样:

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;

System.DirectoryServices.AccountManagement命名空间提供了跨多个主要存储区域(Active Directory Domain Services(AD DS)、Active Directory Lightweight Directory Services(AD LDS)和Machine SAM(MSAM))对用户、计算机和组安全主体进行统一访问和操作的功能。


不是真的,@MethodMan。当然 Response.Write 或者 Debug.Write 更常用,但你仍然可以使用 Console 输出。 - Jeremy Thompson
System.DirectoryServices.AccountManagement比DirectoryEntry慢吗? - Kiquenet
@Kiquenet,我无法回答你的问题,因为我没有检查过。 - Denis Bubnov
1
"User" 属于哪个命名空间? - ataraxia
第二个代码片段中 PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 的目的是什么?看起来 ctx 在那里没有被使用。 - Doc Brown
显示剩余2条评论

6
using System.DirectoryServices.AccountManagement;

string fullName = null;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context, User.Identity.Name))
    {
        if (user != null)
        {
            fullName = user.DisplayName;
            lbl_Login.Text = fullName;
        }
    }
}

谢谢,这也起作用了,我只需要将“User.Identity.Name”替换为您手动放置的用户名称即可。 - Hans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接