简体   繁体   中英

C# DirectoryEntry find all users with a specific attribute (wWWHomePage)

What would be the best way in C# to use directory entry to find all users with the attribute wWWHomePage filled in.

I am able to see if a specific user has it but I have not used Directory Entry to search all users for something like this.

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, myDomain, Login.authUserName, Login.authPassword);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
if (user != null) {
    DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);
    if (de != null) {
        string whatIWant = de.Properties["wWWHomePage"].Value.ToString();
    }
}

use DirectoryEntry with DirectorySearcher and specify the search Filter to get what you want.

the Filter template you want is:

(&(objectClass=user)(objectCategory=person)(PROPERTY_NAME=SEARCH_TERM))

where PROPERTY_NAME is the property you want to search in, and SEARCH_TERM is the value. you could use the * as a wildcard search, it would give you all objects that has this property.

here is a quick example:

// set the properties you need.
var propertiesToLoad = new string[] { "sAMAccountName", "wWWHomePage" };

using(var searcher = new DirectorySearcher(new DirectoryEntry(ldap), "(&(objectClass=user)(objectCategory=person)(wWWHomePage=*))", propertiesToLoad))
{
    foreach (SearchResult result in searcher.FindAll())
    {
        if(result == null) continue;
    
        var samAccount = result.Properties["sAMAccountName"][0];
        
        var wWWHomePage = result.Properties["wWWHomePage"][0];
        
        // complete the code with your logic  
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM