Search code examples
c#winformsactive-directorydirectorysearcher

Searching active directory doesn't pull up the user record when applying a specific filter


DirectoryEntry deEntry = new DirectoryEntry("LDAP://test.com");
DirectorySearcher dsSearcher = new DirectorySearcher(deEntry);
dsSearcher.Filter = "(&(objectclass=user)(objectcategory=person))";

When I apply that filter, the user doesn't show up. But I've checked his attributes and those properties have those values.

But when I add his last name in the filter, he does show up.

dsSearcher.Filter = "(&(objectclass=user)(objectcategory=person)(sn=harper))";

Here is a picture with the deubg info that shows that his attributes are set correctly.

enter image description here

I have no idea what's going on. Any ideas?


Solution

  • 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:

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

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

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