Get Active Directory Groups and Users programmatically

To get Active Directory groups and users we need to reference System.DirectoryServices.AccountManagement in the project.

Get Groups from Active Directory

The method listed below will return list of all group names from Active Directory.
ServerName of the domain controller should be provided as well as UserName and Password for an account with sufficient rights to list the Active Directory groups.

public List<String> GetADGroups()
{
	List<String> result = new List<String>();

	PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ServerName, UserName, Password);
	GroupPrincipal findAllGroups = new GroupPrincipal(ctx, "*");
	PrincipalSearcher ps = new PrincipalSearcher(findAllGroups);
	foreach (Principal group in ps.FindAll())
	{
		result.Add(group.Name);
	}

	return result;
}

Get Users from Active Directory

The method listed below will return list of all users members of a given Active Directory group including the members of all nested subgroups.
ServerName of the domain controlled should be provided as well as UserName and Password for an account with sufficient rights to list the Active Directory groups and users.

public List<String> getGroupUsers(String strGroup)
{
	List<String> groupMembers = new List<String>();

	PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ServerName, UserName, Password);

	GroupPrincipal myGroup = GroupPrincipal.FindByIdentity(ctx, strGroup);

	if (myGroup != null)
	{
		//calling GetMembers with 'true' flag will get all users including members of nested groups
		PrincipalSearchResult<Principal> allMembers = myGroup.GetMembers(true);

		foreach (Principal principal in allMembers)
		{
			//get properties you need from Principal object
			String loginName = principal.SamAccountName;
			groupMembers.Add(loginName);
		}
	}
	else
	{
		throw new Exception("AD group not found.");
	}

	return groupMembers;
}

Advertisements

3 Responses to Get Active Directory Groups and Users programmatically

  1. Pingback: Get, Add or Remove SharePoint groups and users programmatically | Naim's Blog

  2. Anonymous says:

    Hi, I am having an issue with the code Get Users from Active Directory when trying strGroup is an AD group within my domain that contains members that are in another domain.

    See: http://stackoverflow.com/questions/32098273/get-active-directory-groups-and-users-programmatically-error-returning-users-o

    Any ideas on how to fix this?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: