Accessing Active Directory without specifying LDAP path
I’m writing up a class that wraps all of the functionality I need for accessing AD in one place.
So how do I get the LDAP path to the domain controller?
It’s easy – just get it from AD itself. Here’s the code:
using (DirectoryEntry rootDse = (PreAuthenticate ? new DirectoryEntry("LDAP://rootDSE", Username, Password) : new DirectoryEntry("LDAP://rootDSE")))
{
if (null == rootDse)
{
throw new ApplicationException("Can't connect to LDAP://rootDSE. Please make sure that the computer on which you're trying to run the component is a member of the domain and is currently connected to at least one DC.");
}
TypedPropertyValueCollection<string> prRootDse = new TypedPropertyValueCollection<string>(rootDse, "defaultNamingContext");
TypedPropertyValueCollection<string> prDomainName = new TypedPropertyValueCollection<string>(rootDse, "dnsHostName");
RootDSE = prRootDse.Value;
DomainName = prDomainName.Value;
}
Then you can get the LDAP Path like this:
static string LdapPath
{
[System.Diagnostics.DebuggerStepThrough]
get
{
return string.Format("LDAP://{0}/{1}", DomainName, RootDSE);
}
}
The other interesting thing here's the TypedPropertyValueCollection<T> which I've used to whar the access to System.DirectoryServices.DirectoryEntry's properties.
With that I won't have to check for the entry being != null, then casting it to something, etc. Here's the example code:
namespace SofiaDev.DirectoryServices
{
class TypedPropertyValueCollection<T> where T: class
{
System.DirectoryServices.PropertyValueCollection m_property;
public TypedPropertyValueCollection(System.DirectoryServices.PropertyValueCollection property)
{
m_property = property;
}
public TypedPropertyValueCollection(System.DirectoryServices.DirectoryEntry directoryEntry, string propertyName)
{
m_property = directoryEntry.Properties[propertyName];
}
public T Value
{
get
{
return m_property.Value as T;
}
}
public string PropertyName
{
get
{
return m_property.PropertyName;
}
}
public bool IsNull
{
get
{
return ((null != m_property) && (null != m_property.Value));
}
}
}
}
The complete source of two classes can be found in the attachment of the post.
Also in there you can find a couple of quick Find methods (one for searhing user by principal name and one for searching users by email address.