Posts Access Active Directory from Sharepoint

Access Active Directory from Sharepoint

Here is the sample code thar you can use to access Active Directory details from a sharepoint site,

DirectoryEntry oDE;

oDE = new DirectoryEntry(“LDAP://,”ADusername”,”ADpassword”,AuthenticationTypes.Secure);

DirectoryEntry de = oDE;

DirectorySearcher deSearch = new DirectorySearcher();

deSearch.Filter = “(&(objectClass=user)(SAMAccountName=” + SPContext.Current.Web.CurrentUser.LoginName + “))”;

deSearch.SearchScope = SearchScope.Subtree;

SearchResult results = deSearch.FindOne();

if (!(results == null))


de = new DirectoryEntry(results.Path,”AD username”,”AD password”,AuthenticationTypes.Secure);

//if you know the propertyname you want to get value from you can use this


//this code will loop thru all the properties in active directory

ResultPropertyCollection propertiesCollection;

propertiesCollection = results.Properties;

//loop thru all the properties in AD

foreach (string currentProperty in propertiesCollection.PropertyNames)


Response.Write(“Property Name: ” + currentProperty);

//loop thru all the sub properties

foreach (Object thisCollection in propertiesCollection[currentProperty])


Response.Write(thisCollection.ToString() + “




The above code reads and writes the values of the properties from the Active directory for the current user.

But to be able to run the above code you need to make sure that you import System.DirectoryServices,

<%@ Import Namespace=”System.DirectoryServices” %>

Also you need to make sure Web.config has an entry for the System.DirectoryServices in its Assemblies Section,

<add assembly=”System.DirectoryServices, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089″ />
This post is licensed under CC BY 4.0 by the author.