Retrieving User Name from Active Directory

205 Views Asked by At

I am trying to retrieve the User Name from Active Directory. I have found this piece of code to try however, it does not recognize the User portion of User.Identity.Name. I have looked to see if I need to add another reference or assembly however I have not seen anything. Is there a better way of getting the User Name from Active Directory?

static string GetUserName(){

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

    }
2

There are 2 best solutions below

8
Igor Quirino On BEST ANSWER

You can use WindowsIdentity.GetCurrent

using System.Security.Principal;

static string GetUserName()
{
    WindowsIdentity wi = WindowsIdentity.GetCurrent();

    string[] parts = wi.Name.Split('\\');

    if(parts.Length > 1) //If you are under a domain
        return parts[1];
    else
        return wi.Name;
}

Usage:

string fullName = GetUserName();

Happy to help you!

0
marc_s On

How about:

public string GetUserName()
{
    string name = "";

    using (var context = new PrincipalContext(ContextType.Domain))
    {
        var usr = UserPrincipal.Current;

        if (usr != null)
        {
            name = usr.DisplayName;
        }
    }
}