DirectorySearcher Filter

后端 未结 1 521
醉酒成梦
醉酒成梦 2020-12-15 07:04

When I run this query

// Next row is used to login to AD
DirectoryEntry entry = GetEntry(domain, adminUser, adminPassword);
// Here starts the query
Director         


        
相关标签:
1条回答
  • 2020-12-15 07:43

    If you want to query just that then you should bind to that container in your initial connect:

    // Next row is used to login to AD
    string ldapPath = "LDAP://OU=Ingegneria,DC=xxx,DC=xxx";
    DirectoryEntry searchRoot = GetEntry(ldapPath, adminUser, adminPassword);
    
    // Here starts the query
    DirectorySearcher search = new DirectorySearcher(searchRoot)
    {
        SearchScope = SearchScope.Subtree,
        Filter = "(&" +
            "(objectClass=user)" +
            "(givenname=s*)" +
            "(samaccountname=*100)" +
        ")"
    };
    
    search.PropertiesToLoad.Add("distinguishedname");
    SearchResultCollection result = search.FindAll();
    

    That way, you also massively reduce the space in AD that needs to be searched, thus speeding up your search.

    And if you're using .NET 3.5 or newer, you can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

    // create your domain context
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=Ingegneria,DC=xxx,DC=xxx");
    
    // define a "query-by-example" principal - here, we search for a UserPrincipal 
    UserPrincipal qbeUser = new UserPrincipal(ctx);
    qbeUser.GivenName = "s*";
    qbeUser.SamAccountName = "*100";
    
    // create your principal searcher passing in the QBE principal    
    PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
    
    // find all matches
    foreach(var found in srch.FindAll())
    {
        // do whatever here - "found" is of type "Principal"
        UserPrincipal userFound = found as UserPrincipal;
    
        if(userFound != null)
        {
           // do something with your user principal here....
        }
    }
    

    If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement

    0 讨论(0)
提交回复
热议问题