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

Van*_*nel 3 .net c# adsi .net-4.0 active-directory

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

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

PrincipalContext principalContext =
    new PrincipalContext(ContextType.Domain,
                            domainName.Trim(),
                            domainContainer.Trim());
Run Code Online (Sandbox Code Playgroud)

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
Run Code Online (Sandbox Code Playgroud)

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

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Ash*_*ore 9

使用时

var context = new PrincipalContext(ContextType.Domain);
Run Code Online (Sandbox Code Playgroud)

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

使用时

var context = new PrincipalContext(ContextType.Domain, domainName, domainContainer);
Run Code Online (Sandbox Code Playgroud)

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

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