2

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

    }
Ethel Patrick
  • 885
  • 7
  • 18
  • 38

2 Answers2

1

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!

Igor Quirino
  • 1,187
  • 13
  • 28
0

How about:

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

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

        if (usr != null)
        {
            name = usr.DisplayName;
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459