I have three or more domains like main.com
, sub.main.com
, sub2.main.com
and etc
I have a code:
using (PrincipalContext ctx =
new PrincipalContext(ContextType.Domain, "ADServer",
"dc=main,dc=com", ContextOptions.Negotiate))
{
UserPrincipal u = new UserPrincipal(ctx);
u.UserPrincipalName = "*" + mask + "*";
using (PrincipalSearcher ps = new PrincipalSearcher(u))
{
PrincipalSearchResult<Principal> results = ps.FindAll();
List<ADUser> lst = new List<ADUser>();
foreach (var item in results.Cast<UserPrincipal>().Take(15))
{
byte[] sid = new byte[item.Sid.BinaryLength];
item.Sid.GetBinaryForm(sid, 0);
ADUser us = new ADUser()
{
Sid = sid,
Account = item.SamAccountName,
FullName = item.DisplayName
};
lst.Add(us);
}
}
return lst;
}
But it searches within only one domain: main.com
.
How can I search records in all domains at one time?
You should use GC instead of LDAP. It searches along whole Domain Forest
To actually use System.DirectoryServices.AccountManagement to do the search, specify the domain as such:
From When do I need a Domain Name and a Domain Container to create a PrincipalContext?
Here is a way to find all your domains from the root one :
Then foreach domain, you can look for what you need.