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 getting 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With