我何时需要域名和域容器来创建PrincipalContext?

我正在开发一个C#.NET Framework库来访问活动目录。

我要做的一件事是获得所有AD用户,我看到:

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName.Trim(), domainContainer.Trim()); 

 PrincipalContext principalContext = new PrincipalContext(ContextType.Domain); 

使用以下代码返回相同的用户:

 // 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); } } 

我何时需要使用域名和域容器?

使用时

 var context = new PrincipalContext(ContextType.Domain); 

它将连接到当前上下文的域,通常是运行应用程序的用户登录的域,或者如果当前上下文是未连接到域的本地用户,则将引发exception。

使用时

 var context = new PrincipalContext(ContextType.Domain, domainName, domainContainer); 

如果当前上下文具有权限或您提供有效凭据,则domain属性允许您连接到当前上下文之外的域。 因此,例如,在林中存在多个域或域信任的环境中,您可以指定另一个域来运行查询,而不是用户所属的域。

容器属性将使用该DomainContext所有查询限制到指定的容器。

上下文用于创建一个目录条目:

 new DirectoryEntry("LDAP://domain_name/container") 

或者当没有容器时:

 new DirectoryEntry("LDAP://domain_name/rootDse") 

您可以省略域名,但我建议始终包含它,因为我过去遇到过它(一些随机抛出的exception)。

如果要将搜索限制为特定OU,则应包括容器。