Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to fetch all users from active directory

0.00/5 (No votes)
6 Oct 2014 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here