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;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s