Search This Blog

Friday, September 3, 2010

How to get all users in an Active Directory Group

public static DataSet GetUsersForGroup(string GroupName)
DataSet dsUser = new DataSet();
DirectoryEntry de = GetDirectoryObject();

//create instance fo the direcory searcher
DirectorySearcher deSearch = new DirectorySearcher();

//set the search filter
deSearch.SearchRoot =de;
deSearch.Filter = "(&(objectClass=group)(cn=" + GroupName +"))";

//get the group result
SearchResult results= deSearch.FindOne();

//Create a new table object within the dataset
DataTable tbUser = dsUser.Tables.Add("Users");

//Create default row
DataRow rwDefaultUser = tbUser.NewRow();
rwDefaultUser ["UserName"]= "0";
rwDefaultUser ["DisplayName"]="(Not Specified)";
rwDefaultUser ["EMailAddress"]="(Not Specified)";

//if the group is valid, then continue, otherwise return a blank dataset
if(results !=null)
//create a link to the group object, so we can get the list of members
//within the group
DirectoryEntry deGroup= new DirectoryEntry(results.Path,ADAdminUser,ADAdminPassword,AuthenticationTypes.Secure);
//assign a property collection
System.DirectoryServices.PropertyCollection pcoll = deGroup.Properties;
int n = pcoll["member"].Count;

//if there are members fo the group, then get the details and assign to the table
for (int l = 0; l < n ; l++)
//create a link to the user object sot hat the FirstName, LastName and SUername can be gotten
DirectoryEntry deUser= new DirectoryEntry(ADFullPath + "/" +pcoll["member"][l].ToString(),ADAdminUser,ADAdminPassword,AuthenticationTypes.Secure);

//set a new empty row
DataRow rwUser = tbUser.NewRow();

//populate the column
rwUser["UserName"]= GetProperty(deUser,"cn");
rwUser["DisplayName"]= GetProperty(deUser,"givenName") + " " + GetProperty(deUser,"sn");
rwUser["EMailAddress"]= GetProperty(deUser,"mail");
//append the row to the table of the dataset

//close the directory entry object


return dsUser;

No comments:

Post a Comment