dotnet - Get All Active Directory Users in a Group
Published: Dotnet Estimated reading time: ~1 minutes
Use the following handy method to get all users in an AD group .NET 3.5
Add a reference to
System.DirectoryServices.AccountManagement
public static List<UserPrincipal> GetAllUsersInGroup(string domain, string groupname)
{
List<UserPrincipal> result = new List<UserPrincipal>();
using (var context = new PrincipalContext(ContextType.Domain, domain))
using (var group = GroupPrincipal.FindByIdentity(context, groupname))
{
if (group != null)
{
result.AddRange(group.GetMembers(true).Cast<UserPrincipal>().ToList());
}
}
return result;
}
private static string GetADStatus(int inputField)
{
// Assume the user is disabled
string result = "Disabled";
// Declare the hex for the accountDisabled flag
int accountDisabled = 0x00000002; // https://msdn.microsoft.com/en-us/library/ms680832%28v=vs.85%29.aspx
// Do a bitwise and against the input field and the account disabled mask
int resultArray = inputField & accountDisabled;
// Compare the results of the bitwise and operation to see if the account disabled flag was set
if (resultArray == accountDisabled)
{
result = "Disabled";
}
else
{
result = "Active";
}
return result;
}
References
http://www.codeproject.com/Tips/599697/Get-list-of-Active-Directory-users-in-Csharp http://www.dotnetactivedirectory.com/Understanding_LDAP_Active_Directory_User_Object_Properties.html https://msdn.microsoft.com/en-us/library/ms680832%28v=vs.85%29.aspx https://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.principalcontext(v=vs.110).aspx