Retrieve users and groups from Active Directory (AD)

Below code describes how to get all users and all groups from active directory (AD Server) Using System.DirectoryServices

Steps:-

  1. Add System.Directoryservices.dll and System.Directoryservices.AccountManagement.dll which provides access to active directory.
  2. Using System.DirectoryServices.AccountManagement
  3. I have used a generic list (collection of string) to store account name of user and group.

 

class Program

{

static void Main(string[] args)

{

 List<string> _userOrGroupColl = new List<string>();

 PrincipalContext pContext = new PrincipalContext (ContextType.Domain, YOUR_DOMAIN);

//For User

 UserPrincipal userPrincipal = new UserPrincipal (pContext);

PrincipalSearcher userSearch = new PrincipalSearcher (userPrincipal);

//For Group

GroupPrincipal grpPrincipal = new GroupPrincipal (pContext);

 PrincipalSearcher grpSearch = new PrincipalSearcher (grpPrincipal);

foreach (UserPrincipal result in userSearch.FindAll())

{

if (result != null)

{

if (result.SamAccountName!= null)

 _userOrGroupColl.Add(result.SamAccountName);

}

}

foreach (GroupPrincipal result in grpSearch.FindAll())

{

if (result != null)

{

 if (result.SamAccountName != null)

_userOrGroupColl.Add(result.SamAccountName);

}

}

}

}

Tags: , , ,

1 thought on “Retrieve users and groups from Active Directory (AD)

Leave a Reply

Your email address will not be published. Required fields are marked *