简体   繁体   English

从 Active Directory 获取用户名

[英]Get Name of User from Active Directory

I need to show only the name of a user from Active Directory, I am using我只需要显示来自 Active Directory 的用户名,我正在使用

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

This shows the users name but not the real name of the user, I've checked other questions and answers related here but I've not gotten the solution.这显示了用户名但不是用户的真实姓名,我已经检查了此处相关的其他问题和答案,但我还没有得到解决方案。

Is there any property just as "User.Identity.Name" to get only the name of the user?有没有像“User.Identity.Name”这样的属性来只获取用户的名字?

You want name of a user from active directory.您需要活动目录中的用户名。 Try code like this:试试这样的代码:

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

or this from social.msdn.microsoft.com :或来自social.msdn.microsoft.com

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

or may be it:或者可能是:

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

The System.DirectoryServices.AccountManagement namespace provides uniform access and manipulation of user, computer, and group security principals across the multiple principal stores: Active Directory Domain Services (AD DS), Active Directory Lightweight Directory Services (AD LDS), and Machine SAM (MSAM). System.DirectoryServices.AccountManagement 命名空间提供跨多个主体存储区的用户、计算机和组安全主体的统一访问和操作:Active Directory 域服务 (AD DS)、Active Directory 轻型目录服务 (AD LDS) 和机器 SAM( MSAM)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM