Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

c# - When do I need a Domain Name and a Domain Container to create a PrincipalContext?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...