I'm developing a C# .NET Framework library to access active directory.
One of the things that I have to do is to get all AD users, and I see that:
PrincipalContext principalContext =
new PrincipalContext(ContextType.Domain,
domainName.Trim(),
domainContainer.Trim());
And
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
Returns the same users with this code:
// define a "query-by-example" principal - here, we search for all users
UserPrincipal qbeUser = new UserPrincipal(principalContext);
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
// find all matches
foreach (var found in srch.FindAll())
{
UserPrincipal user = found as UserPrincipal;
if (user != null)
{
Console.WriteLine(user.SamAccountName);
}
}
When do I need to use a Domain Name and a Domain Container?
When using
var context = new PrincipalContext(ContextType.Domain);
It will connect to the domain of the current context, usually the domain the user who ran the application is logged into, or will throw an exception if the current context is a local user not connected to a domain.
When using
var context = new PrincipalContext(ContextType.Domain, domainName, domainContainer);
The domain property allows you to connect to a domain other than the one of the current context, assuming the current context has permissions or you supply valid credentials. So for example in an environment where there is multiple domains in a forest or domain trusts in place, you can specify another domain to run queries against instead of the one the user is a member of.
The container properties limits all queries using that DomainContext
to the specified container.