How to get a username in Active Directory from a display name in C#?

前端 未结 2 527
遇见更好的自我
遇见更好的自我 2021-02-01 07:10

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 durin

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 07:46

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

提交回复
热议问题