Wednesday, October 14, 2009

Getting users for an AD Group

For one of our requirements , We needed to pull all the users for a specific AD Group.

You know me , right.. always ready to code something... :-)

I am using HostingEnvironment.Impersonate() to be able to make the code run ASP.Net Application Pool context. If you are using it from console application, you may not need this.


using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.Reflection;
using System.Web.Hosting;

public static List<string> GetGroupMembers(string domainName, string ADConnectionString, string strGroup)
List<string> groupMembers = new List<string>();

using (HostingEnvironment.Impersonate())
if (string.IsNullOrEmpty(ADConnectionString))
throw new Exception("ADConnectionString value is Empty");

//connects to the given AD based on given AD string
DirectoryEntry ent = new DirectoryEntry("LDAP://" + ADConnectionString);

//ones connected to the AD it searches for given/named group
DirectorySearcher srch = new DirectorySearcher("(CN=" + strGroup + ")");

SearchResult rs = srch.FindOne();

ResultPropertyCollection resultPropColl = rs.Properties;

foreach (Object memberColl in resultPropColl["member"])
//get the info about specific AD user from AD
DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);

// PrintDirectoryEntryProperties(gpMemberEntry);
System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;

object objVal = userProps["sAMAccountName"].Value;

if (null != objVal)
if (gpMemberEntry.SchemaClassName == "user")
groupMembers.Add(domainName + "\\" + objVal.ToString());
//// Un-comment and test this section for recursively finding users
// groupMembers.AddRange(GetGroupMembers(domainName, ADConnectionString, objVal.ToString()));
catch (Exception ex)
// Log.Error(ex.ToString());
return groupMembers;