Ethel Patrick
Ethel Patrick

Reputation: 975

Retrieving User Name from Active Directory

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

    }

Upvotes: 2

Views: 221

Answers (2)

Igor Quirino
Igor Quirino

Reputation: 1195

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!

Upvotes: 1

marc_s
marc_s

Reputation: 755491

How about:

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

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

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

Upvotes: 0

Related Questions