Monday, December 9, 2013

C# Code to read Active directory attributes for a user

Juts add the below code to a Windows/Web solution and assign the results to a label in you form

using System.DirectoryServices;
using System.Collections;

DirectoryEntry dir = new DirectoryEntry();
dir.Path = "LDAP://YourActiveDirServername ";
DirectorySearcher sea = new DirectorySearcher(dir);
sea.Filter = "(sAMAccountName=user)";
SearchResult seares = sea.FindOne();
StringBuilder str = new StringBuilder();
System.DirectoryServices.ResultPropertyCollection prop = seares.Properties;
ICollection coll = prop.PropertyNames;
IEnumerator enu = coll.GetEnumerator();
while (enu.MoveNext())
{
str.Append(enu.Current + " = " + seares.Properties[enu.Current.ToString()][0] + "\n");
}

label1.Text = str.ToString();