Get Active Directory Root Programmatically

Use RootDSE and defaultNamingContext as opposed to hard-coding the LDAP string:

DirectoryEntry _directoryEntryRoot= new DirectoryEntry("LDAP://RootDSE"); //Get AD Root
 string _context= _directoryEntryRoot.Properties["defaultNamingContext"][0].ToString();//Get Context
 _ldapPath= "LDAP://" + _context;//Complete baseLDAP stringstring _filter = String.Format("(&(objectClass=user)(objectCategory=person)(sAMAccountName={0}))", User.Identity.Name.Split(new char[] { '\\' })[1]);
DirectoryEntry _directoryEntry= new DirectoryEntry(_ldapPath, null, null, AuthenticationTypes.Secure);//sets search root to root path
using (_directoryEntry)//current user
{
string user = Environment.UserName;
DirectorySearcher _directorySearcher = new DirectorySearcher(directoryEntry, _filter, attribsToLoad, SearchScope.Subtree);
_directorySearcher.SizeLimit = 1;
_directorySearcher.FindOne();
}

Advertisements