Wednesday, July 29, 2009

How to pull Active Directory Users and populate into a drop down.

Sometimes it is very hard to get it done, use this code to pull all the users from your active directory.


private void populateUsers()
{
ddlUsers.Items.Clear();

using (HostingEnvironment.Impersonate()) // To break the security for some time
{
DirectoryEntry entry = new DirectoryEntry("your AD server name");
DirectorySearcher searcher = new DirectorySearcher(entry);
try
{

searcher.Filter = " (&(objectClass=user)(objectCategory=person)(DN=*) "; //DN is the distinguished name of the AD user

foreach (SearchResult sResultSet in searcher.FindAll())
{
ListItem item = new ListItem();

item.Text = GetProperty(sResultSet, "givenName") + SPACE + GetProperty(sResultSet, "sn"); // sn - Surname
item.Value = "your domain" + GetProperty(sResultSet, "sAMAccountName"); // sAMAccountName - login name

ddlUsers.Items.Add(item);
}

ddlUsers.Items.Insert(0, "Select User");
}
catch (Exception ex)
{
throw new AppException(ex);
}
}
}
public static string GetProperty(SearchResult searchResult, string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
{
return searchResult.Properties[PropertyName][0].ToString();
}
else
{
return string.Empty;
}
}

Hope this helps!!

No comments:

Post a Comment