Retrieve users and groups from Active Directory (AD)

  • Posted by: Softree Technology

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

}

}

}

}

Author: Softree Technology

Leave a Reply

1 Comment