How can I search Active Directory by username using C#?

后端 未结 5 1803
名媛妹妹
名媛妹妹 2021-01-05 03:53

I\'m trying to search active directory by the username \'admin\'. I know for a fact that there is a user with that username in the directory, but the search keeps coming bac

5条回答
  •  遥遥无期
    2021-01-05 04:28

    If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

    • Managing Directory Security Principals in the .NET Framework 3.5
    • MSDN docs on System.DirectoryServices.AccountManagement

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

    // set up domain context
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "admin");
    
    if(user != null)
    {
       // do something here....     
    }
    

    With this code, you'll be searching for that user by the following attributes:

    • DistinguishedName : The identity is a Distinguished Name (DN).
    • Guid: The identity is a Globally Unique Identifier (GUID).
    • Name: The identity is a name.
    • SamAccountName: The identity is a Security Account Manager (SAM) name.
    • Sid: The identity is a Security Identifier (SID) in Security Descriptor Definition Language (SDDL) format.
    • UserPrincipalName: The identity is a User Principal Name (UPN).

    The new S.DS.AM makes it really easy to play around with users and groups in AD!

提交回复
热议问题