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.PropertiesToLoad.Add("cn");
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");
tbUser.Columns.Add("UserName");
tbUser.Columns.Add("DisplayName");
tbUser.Columns.Add("EMailAddress");

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

//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
tbUser.Rows.Add(rwUser);

//close the directory entry object
deUser.Close();

}
de.Close();
deGroup.Close();
}

return dsUser;
}

No comments:

Post a Comment