Search user of specific domain name
Usually, we use a LDAP search filter to find a user. The filter like "(SAMAccountName=user alias)".
But there is a special situation is: The domain what the LDAP path assign has several sub-domains, and there are several users of these sub-domains have same alias.
E.g.
The LDAP path is "GC://DC=root, DC=com".
There are two sub-domains of root domain:
GC://DC=sub1, DC=root, DC=com
GC://DC=sub2, DC=root, DC=com
There are two users are:
sub1\username
sub2\username
We cannot write a filter like "(!(DomainName=domain name)(SAMAccountName=user alias))". If we use the filter "(SAMAccountName=user alias)" to search from "GC://DC=root, DC=com", we will get two results.
Which is our real target?
So, we must identify the distinguishedName of the user with regular expression "DC *=[^,]+" to get the use's domain name.
SearchResultCollection results = mySearcher.FindAll();
// check domain name
foreach (SearchResult result in results)
{
string dn = result.Properties["distinguishedName"][0].ToString();
Match m = Regex.Match(dn, "DC *=[^,]+");
string mValue = Regex.Replace(m.Value, @"[\s]", "", RegexOptions.IgnoreCase);
if (string.Compare(mValue, "dc=" + userDomain, true) == 0)
{
// The target is found
}
}