I've been recommended to use System.DirectoryServices.Protocols
to be able to support connecting to LDAP servers other than Active Directoy here.
Unfortunately, I have not been able to search the directory properly. I'd like to be able to get a certain attribute for a user (e.g. mail
). This is easily done in System.DirectoryServices
namespace by using DirectorySearcher
class. How can I achieve the same in System.DirectoryServices.Protocols
namespace. Here's what I have so far:
var domainParts = domain.Split('.');
string targetOu = string.Format("cn=builtin,dc={0},dc={1}", domainParts[0], domainParts[1]);
string ldapSearchFilter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", username);
// establish a connection to the directory
LdapConnection connection = new LdapConnection(
new LdapDirectoryIdentifier(domain),
new NetworkCredential() { UserName = username,
Password = "MyPassword" });
SearchRequest searchRequest = new SearchRequest(
targetOu, ldapSearchFilter, SearchScope.OneLevel, new[] {"mail"});
This code raises exception of type DirectoryOperationException
with message The object does not exist
.
I suspect there's something wrong with my targetOu
and ldapSearchFilter
variables.
Thanks.