Enterprise Solutions


How to get members of a group using DirectoryServices

This article will show you how to use DirectoryServices namespace classes to get members of a windows group. A lot of users have been requesting to show how LDAP provider can be used with DirectoryServices classes instead of WinNT provider. This article shows the use of LDAP provider. The code sample shown in this article is not state of the art implementation but it should give you an idea on how the mentioned task can be accomplished.

private void Page_Load(object sender, System.EventArgs e)
{
	StringCollection groupMembers = this.GetGroupMembers("pardesifashions","Debugger Users");
	foreach (string strMember in groupMembers)
	{
		Response.Write("<br><b>" + strMember + "</b>");
	}
}

public StringCollection GetGroupMembers(string strDomain, string strGroup)
{
	StringCollection groupMemebers = new StringCollection();
	try
	{
		DirectoryEntry ent = new DirectoryEntry("LDAP://DC=" + strDomain + ",DC=com");
		DirectorySearcher srch = new DirectorySearcher("(CN=" + strGroup + ")");
		SearchResultCollection coll = srch.FindAll();
		foreach (SearchResult rs in coll)
		{
			ResultPropertyCollection resultPropColl = rs.Properties;
			foreach( Object memberColl in resultPropColl["member"])
			{
				DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);
				System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;
				object obVal = userProps["sAMAccountName"].Value;
				if (null != obVal)
				{
					groupMemebers.Add(obVal.ToString());
				}
			}
		}
	}
	catch (Exception ex)
	{
		Trace.Write(ex.Message);
	}
	return groupMemebers;
}							
							
Home     About us     Contact us
Copyright    Privacy Policy
Copyright (c) Pardesi Services LLC