Get username from Active Directory

I need to show only the username from Active Directory, I use

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

This shows the username, but not the real username, I checked other questions and answers related to this, but I did not get a solution.

Is there any property like "User.Identity.Name" to get only the username?

+4
source share
2 answers

You want the username from the active directory. Try the following code:

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 is from social.msdn.microsoft.com :

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

or maybe it:

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

System.DirectoryServices.AccountManagement , : Active Directory (AD DS), Active Directory (AD LDS) Machine SAM (MSAM).

+9
using System.DirectoryServices.AccountManagement;

string fullName = null;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context,"hajani"))
    {
        if (user != null)
        {
            fullName = user.DisplayName;
            lbl_Login.Text = fullName;
        }
    }
}
+2

Source: https://habr.com/ru/post/1652922/


All Articles