17

I want to be able to obtain the userid of a user in Active Directory using the display name of that user. The display name is obtained from a database, and has been stored during that user's session using the following code to obtain the display name:

using System.DirectoryServices.AccountManagement;

    private string GetDisplayName()
    {
        // set up domain context
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

        // find currently logged in user
        UserPrincipal user = UserPrincipal.Current;

        return user.DisplayName;
    }

This time around, I would like to have a method named GetUserIdFromDisplayName() that returns the Active Directory login name. Any ideas?

3
  • 1
    I haven't verified it, so I'm not 100% sure, but I think you want the SamAccountName property. Commented Mar 23, 2012 at 19:37
  • Do you think, this is possible? I doubt that user display names are unique. Would possibly lead to multipe results.
    – Uwe Keim
    Commented Mar 23, 2012 at 20:37
  • True. I now consider using GUIDs instead using the answer below. Commented Mar 23, 2012 at 20:41

2 Answers 2

37

I believe you can do it much more easily than with David's answer by using the built-in functionality of the System.DirectoryServices.AccountManagement (S.DS.AM) namespace.

Basically, you can define a domain context and easily find users and/or groups in AD:

using System.DirectoryServices.AccountManagement;

private string GetUserIdFromDisplayName(string displayName)
{
    // set up domain context
    using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
        // find user by display name
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, displayName);

        // 
        if (user != null)
        {
             return user.SamAccountName;
             // or maybe you need user.UserPrincipalName;
        }
        else
        {
             return string.Empty;
        }
    }
}

I don't see any need to go to the underlying DirectoryEntry object, really - unless none of the properties of the UserPrincipal really are what you're looking for.

PS: if the search by display name shouldn't work (I don't have an AD at hand to test it right now) - you can always also use the PrincipalSearcher to find your user:

using System.DirectoryServices.AccountManagement;

private string GetUserIdFromDisplayName(string displayName)
{
    // set up domain context
    using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
        // define a "query-by-example" principal - here, we search for a UserPrincipal 
        // and with the display name passed in
        UserPrincipal qbeUser = new UserPrincipal(ctx);
        qbeUser.DisplayName = displayName;

        // create your principal searcher passing in the QBE principal    
        PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

        // find match - if exists
        UserPrincipal user = srch.FindOne() as UserPrincipal;

        if (user != null)
        {
             return user.SamAccountName;
             // or maybe you need user.UserPrincipalName;
        }
        else
        {
             return string.Empty;
        }
    }
}
3
  • 2
    +1, easier and quicker, and finds DOMAIN\USERID entries as well Commented Sep 1, 2014 at 10:04
  • 1
    I was able to find users by their DOMAIN\USERNAME with UserPrincipal.FindByIdentity(ctx, IdentityTypes.SamAccountName, username), so I assume you want to return user.SamAccountName like the code states.
    – Pakman
    Commented Jan 23, 2015 at 5:50
  • FindByIdentit() is find by user principle. User principle is not essentially same as Display Name. If you create a new user with display name "ABC". Later you can change it to "A B C". The user principle will not be updated and above script will not find this user.
    – Mark
    Commented Jan 7, 2019 at 2:23
8

UserPrincipal has a method GetUnderlyingObject() which will return the DirectoryEntry.

Get DirectoryEntry from Principal:

private DirectoryEntry GetDirectoryEntryFromUserPrincipal(Principal user)
{
    return (DirectoryEntry)user.GetUnderlyingObject();
}

Get DirectoryEntry from domain and account name:

private DirectoryEntry GetDirectoryEntryFromDomainAndUsername(string domainName, string userName)
{
    // Get the sid from the NT account name
    var sid = (SecurityIdentifier) new NTAccount(domainName, accountName)
                  .Translate(typeof(SecurityIdentifier));

    // Get the directory entry for the LDAP service account
    var serviceEntry = new DirectoryEntry("LDAP://{address}", "serviceUsername", "servicePassword");

    var mySearcher = new DirectorySearcher(serviceEntry)
        {
            Filter = string.Format("(&(ObjectSid={0}))", sid.Value)
        };

    return mySearcher.FindOne().GetDirectoryEntry();
}

Once you have the DirectoryEntry use the Guid property to get the entry's Object-Guid

private Guid GetObjectGuidFromDirectoryEntry(DirectoryEntry entry)
{
    // return the Guid this is the Object-Guid (ignore NativeGuid)
    return entry.Guid;
}

For tracking a user account in the application against a directory account: always use the Object-Guid as "This value is set when the object is created and cannot be changed."
NT and SAM account names can change if the user changes domains or, more commonly, changes their name (marriage, legal name-change, etc.) and should not be used to track a user.

To get the NT account name (domain\username):

private string GetNTAccountNameFromDirectoryEntry(DirectoryEntry entry)
{
    PropertyValueCollection propertyValueCollection = entry.Properties["objectsid"];

    SecurityIdentifier sid = new SecurityIdentifier((byte[]) propertyValueCollection[0], 0);

    NTAccount ntAccount = (NTAccount)sid.Translate(typeof (NTAccount));

    return account.ToString();
}

To get the SAM-Account-Name (username@domain):

private string GetSAMAccountFromDirectoryEntry(DirectoryEntry entry)
{
    return entry.Properties["Name"].Value;
}

And here's the exhaustive list of all the Active Directory attributes. Use the "Ldap-Display-Name" when getting the value from Properties
e.g. Properties["Ldap-Display-Name"]

Display-Name (FirstName MI LastName) might come in handy.

3
  • Thanks! Then I suppose you have to obtain UserPrincipal objects from an AD group by doing something like this: social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/… Commented Mar 23, 2012 at 20:44
  • That would work. I saw you were using UserPrincipal.Current in your question. This works if the web app is hosted in the domain, using "Windows Security", or is a native app running in a user session. If you can only query AD, then get the directory entry directly by filtering by SAM-Account-Name.
    – David
    Commented Mar 23, 2012 at 21:02
  • Added GetDirectoryEntryFromDomainAndUsername. This might need a bit of tweaking as I'm not in an environment where I can test all this against an AD server.
    – David
    Commented Mar 23, 2012 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.