Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Name of User from Active Directory

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?

like image 785
Hans Avatar asked Aug 29 '16 20:08

Hans


1 Answers

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

like image 100
Denis Bubnov Avatar answered Sep 28 '22 03:09

Denis Bubnov