Skip to content

Instantly share code, notes, and snippets.

@brunomartinspro
Last active Jun 21, 2018
Embed
What would you like to do?
Get Active Active Directory Users based on List of usernames
using System;
using System.Linq;
using System.Collections.Generic;
using System.DirectoryServices;
using BrunoMartinsPro.Data.Interfaces.Utils.ActiveDirectory;
namespace BrunoMartinsPro.Utils.ActiveDirectory
{
public class ADUtils : IADUtils
{
private readonly DirectoryEntry _directoryEntry;
public ActiveDirectoryUtils(DirectoryEntry directoryEntry)
{
_directoryEntry = directoryEntry;
}
/// <summary>
/// Get all ActiveDirectory Users
/// </summary>
public List<string> GetActiveDirectoryUsers(List<string> existingUsernameList)
{
List<string> users = new List<string>();
var usernameQuery = $"(|{String.Join(string.Empty, existingUsernameList.Select(x => $"(SAMAccountName=*{x}*)").ToList())})";
//Create Directory Search
DirectorySearcher search = new DirectorySearcher(_directoryEntry);
//Search for a user that is member of anything and is active
string query = $"(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2){usernameQuery})";
//Apply search query
search.Filter = query;
//Add property SAM ACCOUNT NAME
search.PropertiesToLoad.Add("samaccountname");
//Execute search
SearchResultCollection mySearchResultColl = search.FindAll();
//Add users
foreach (SearchResult result in mySearchResultColl)
{
//Get user
var userToAdd = result.Properties["samaccountname"][0].ToString();
//Add user
users.Add(userToAdd);
}
//return users
return users;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BrunoMartinsPro.Data.Interfaces.Utils.ActiveDirectory
{
public interface IADUtils
{
List<string> GetActiveDirectoryUsers(List<string> existingUsernameList);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment