65.9K
CodeProject is changing. Read more.
Home

How to fetch all users from active directory

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.17/5 (4 votes)

Oct 7, 2014

CPOL
viewsIcon

18614

This tip/code will help in fetching all active directory users name and store in dynamic list.

Introduction

This tip/code will help in fetching all active directory users name and store in dynamic list.

Background

I had a requirement in a MVC project where I had to fetch all the Active directory user names and store the same in a dynamic list.

Code

We need to add System.DirectoryServices.AccountManagement namespace in the project.

List<dynamic> adUsersDetails = new List<dynamic>();

string groupName = "Domain Users";
string domainName = "Your Domain Name"; //Here we need to put the Domain name
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName);

if (grp != null)
{
	foreach (Principal p in grp.GetMembers(false))
	{
		if (p.DisplayName != null)
		{
			dynamic row = new System.Dynamic.ExpandoObject();
			row.Text = p.DisplayName;
			row.Value = p.SamAccountName;
			adUsersDetails.Add(row);
		}
	}

	grp.Dispose();
	ctx.Dispose();
}

Now this list which has all Active directory user's DisplayName and SamAccountName, can be used for populating drop down or in any other way.