Get a user's path within Active Directory using LDAP

Get a user's path within Active Directory

Note: To add or read properties from an Active Directory group you need to have special username and password like an Active Directory admin.

Within Active Directory User could be in OU=Accounts or in OU=Accounts\HR or in OU=Accounts\HR\Recruiters. You can get the USer's path without having to traverse through the entire "Accounts".


string uID = userID.Remove(0, 6).ToUpper();
string folderPath = "";
folderPath = "LDAP://OU=UserAccounts,DC=aaaaa,DC=com";
DirectoryEntry folderEntry;
folderEntry = new DirectoryEntry(folderPath, "Spluser""password");
DirectorySearcher searcher = new DirectorySearcher(folderEntry);
searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))"uID);
searcher.SearchScope = SearchScope.Subtree;
SearchResult result = searcher.FindOne();
if (result != null)
{
   searchpath = result.Path;
}
searcher.Dispose(); folderEntry.Dispose();
return searchpath;

you can read here  about the SearcherScope property offered by the DirectorySearcher.

No comments: