Tuesday, October 7, 2014

How to fetch all users from active directory

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

 
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();
}

No comments:

Post a Comment