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"; 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.