Reputation: 9394
I have the following code to get all users from the ActiveDirectory:
List<string> userIds = new List<string>();
Regex userRegex = new Regex("^user[0-9]{8}z$", RegexOptions.IgnoreCase);
DirectoryEntry rootEntry = new DirectoryEntry("LDAP://mydomain.com");
rootEntry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher searcher = new DirectorySearcher(rootEntry)
{
PageSize = int.MaxValue,
Filter = "(&(objectClass=user)(objectCategory=person))"
};
foreach (SearchResult result in searcher.FindAll())
{
string userId = result.Properties["samaccountname"].Count > 0
? result.Properties["samaccountname"][0].ToString()
: string.Empty;
if (userRegex.IsMatch(userId))
{
userIds.Add(userId);
}
}
This just works fine, but it takes about 50 seconds to get all users from searcher.FindAll()
.
I was wondering if it is possible to move the userRegex to the Filter of the DirectorySearcher
?
I've tried:
Filter = "(&(objectClass=user)(objectCategory=person)(samaccountname=user[0-9]{8}z))"
But then I get no results.
All user-ids have the syntax user56238941z
Upvotes: 0
Views: 1468
Reputation: 40958
LDAP queries don't support RegEx, so you can't get that exact query, but you can get close and then still apply the RegEx after like you're already doing.
You can try using a wildcard in the middle of the query like Oliver suggests (I don't know if AD allows that, so try it - I'm not able to right now) to find accounts where the username starts start with user
and end with z
:
(&(objectClass=user)(objectCategory=person)(sAMAccountName=user*z))
If that doesn't work, you can look for any accounts where the username starts with user
, like this:
(&(objectClass=user)(objectCategory=person)(sAMAccountName=user*))
If that is still returning too many results and hurting performance, you can expand it to return only accounts where the username starts with user
followed by a digit, like this:
(&(objectClass=user)(objectCategory=person)(|(sAMAccountName=user1*)(sAMAccountName=user2*)(sAMAccountName=user3*)(sAMAccountName=user4*)(sAMAccountName=user5*)(sAMAccountName=user5*)(sAMAccountName=user6*)(sAMAccountName=user7*)(sAMAccountName=user8*)(sAMAccountName=user9*)(sAMAccountName=user0*)))
Upvotes: 1