16

I need to show only the name of a user from Active Directory, I am using

 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?

1
  • I will post a simple way to get the full display name
    – MethodMan
    Aug 29, 2016 at 22:00

2 Answers 2

28

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:

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).

7
  • Not true @MethodMan, sure Response.Write or Debug.Write is more common but you can still use Console output. Aug 29, 2016 at 22:07
  • System.DirectoryServices.AccountManagement more slow than DirectoryEntry ?
    – Kiquenet
    Feb 14, 2019 at 10:08
  • @Kiquenet I can't answer to your question because I didn't check it. Mar 6, 2019 at 7:46
  • @DenisBubnov using the same code. how can i fetch that user phone number.? Right-now i getting Email id by using this code (email= usr.EmailAddress;) Mar 27, 2019 at 19:11
  • 1
    Which namespace is "User" from?
    – ataraxia
    Jul 17, 2019 at 13:19
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;
        }
    }
}
1
  • Thanks, this worked too, I just had to add replace "User.Identity.Name" to where you placed manually my users name
    – Hans
    Aug 30, 2016 at 12:52

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.