开发者

Why can't the Active Directory server be contacted via PrincipalContext?

I am facing some problems in accessing Active Directory from my WinForm app. What I want is to create a user and query user from Active Directory.

Here is code snippet for find user:

public bool FindUser(string username)
{
    using (PrincipalContext context = new PrincipalContext(
        ContextType.Domain, 
        this.domainName, 
        this.DomainUserName, 
        this.DomainPassword))
    {                
        UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
        return (user != null) ? true : false;
    }
}

i am unable to create object of PrincipalContext based on given arguments. I am getti开发者_如何学JAVAng this exception:

Exception: The server could not be contacted.

and inner exception states that,

Inner Exception: The LDAP server is unavailable.

where as domain is running. I can ping to it and can also connect to this domain.


You can try next code.

    public bool FindUser2(string userName)
    {
        try
        {
            DirectoryContext context = new DirectoryContext(
                DirectoryContextType.Domain,
                domainName,
                domainName + @"\" + domainUserName,
                domainPassword);
            DirectoryEntry domainEntry = Domain.GetDomain(context).GetDirectoryEntry();
            DirectorySearcher searcher = new DirectorySearcher(domainEntry,
                                                               "(|(objectCategory=user)(cn=" + domainUserName + "))");
            SearchResult searchResult = searcher.FindOne();
            return searchResult != null;
        }
        catch
        {
            return false;
        }
    }


You can use the following code:

objectPath = "LDAP://CN=SC-5515_2,OU=Forus,DC=**MyDomainName**,DC=no";

public static bool Exists(string objectPath)
{
    return DirectoryEntry.Exists(objectPath);
}

This is the code I have used for this. It works fine on testing if any objects exist in Active Directory.


You can also consider using System.DirectoryServices.Protocols for accessing other domains. Bit of a steep learning curve but much faster and more flexible - e.g. you can do proper asynchronous searches.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜