Search code examples
c#.netactive-directoryuserprincipal

How do I get the account name from UserPrincipal?


I am using Active Directory login in one of my Winforms applications. I get a UserPrincipal object but I'm not sure how to get the proper accountname from this object? I can see that there is a SamAccountName that is the same as my account name but it states that this is for old versions of Windows. So how do I get the proper account name no mather old or new Windows systems?

This is the code I use to get the object

if (ADUserName.Length > 0)
    context = new PrincipalContext(ContextType.Domain, ADServer, null,  ADUserName, ADUserPassword);
else
    context = new PrincipalContext(ContextType.Domain, ADServer);

UserPrincipal.FindByIdentity(context, account)

Solution

  • SamAccountName is the "account name" as it was used in Windows even before Active Directory was introduced.

    It's "legacy" in that it has been supplemented by additional info - your "distinguished name" in the LDAP context etc. - but it is the Windows account name ("short name") - and it's still a mandatory field for any new user being created - just use it!

    See User naming attributes for more details on which name is used for what in an AD context.