質問

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.

他のヒント

The context is used to create a directory entry that way:

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

or when there is no container:

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

You can omit the domain name but I would suggest to always include it as I had problems with it in the past (some randomly thrown exceptions).

You should include the container when you want to restrict the search to a specific OU.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top