I use System.DirectoryServices.AccountManagement to query Active Directory for a single user info
public UserInfo FindOne(string samUserName)
{
using (var ctx = new PrincipalContext(ContextType.Domain, "domain.com", "Bob", "pwd"))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, samUserName))
{
if (user != null)
{
// get info about Alice into userInfo
return userInfo;
}
}
}
return null;
}
So if I use var aliceInfo = search.FindOne("alice"); I get info from the directory. Now I need to search a directory (1000+ users) given several user logon names, for example
var userInfos = search.FindMany(/* list of names: alice, jay, harry*/);
How to implement the following method?
public List<UserInfo> FindMany(List<string> samUserNames)
{
...
}
Try this:
string query = "dc=com,dc=domainController,ou=Users"; //this is just an example query, change it to suit your needs
// create your domain context and define the OU container to search in
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "yourDomain", query);
// define a "query-by-example" principal - here, we search for a UserPrincipal (user)
UserPrincipal qbeUser = new UserPrincipal(ctx);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
return srch.FindAll().Select(p => p as UserPrincipal);
This way you can return all users from AD, and then filter out those you don't need. UserPrincipal has a few user related attributes, like Surname and Sid, but if you need to get a value that UserPrincipal doesn't have, you can create an extension method and access any LDAP attribute:
public static String GetProperty(this Principal principal, String property)
{
DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
if (directoryEntry.Properties.Contains(property))
return directoryEntry.Properties[property].Value.ToString() ?? "";
else
return String.Empty;
}
Here is a list of LDAP attributes: https://fsuid.fsu.edu/admin/lib/WinADLDAPAttributes.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With