Below code describes how to get all users and all groups from active directory (AD Server) Using System.DirectoryServices
Steps:-
- Add System.Directoryservices.dll and System.Directoryservices.AccountManagement.dll which provides access to active directory.
- Using System.DirectoryServices.AccountManagement
- 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);
}
}
}
}
That’s a clever answer to a tricky qustoien