Reputation: 38860
I'm trying to get all users that belong to a group in the Active Directory. I want to display the result as a drop down for the site users to select. This is what I have so far:
public IEnumerable<KeyValuePair<string, string>> GetAllMembers(string group)
{
var domainContext = new PrincipalContext(ContextType.Domain);
var group = GroupPrincipal.FindByIdentity(domainContext, group);
return from principal in @group.Members select new KeyValuePair<string, string>(/* need to fill in key and value */);
}
The problem I have is that I am developing this outside of an active directory so cannot really test it yet (long story don't ask). I want to maximise my chances of success when deploying this into a testing environment.
My question is: if I want the key value pair to contain login username (key, ex: "DOMAIN\darkoz"
) and the users real name (value, ex: "Darko Z"
), how do I get those? the Principal
object has at least 5 properties with the word Name
in it so I'm not sure which is which.
Bonus question: is this a generally accepted way of achieving my goal? I realize it is a very simple problem but with my lack of knowledge of Active Directory, I wouldn't be surprised if there was a better way of doing this. Will this work running on an account that is not admin?
Upvotes: 0
Views: 7458
Reputation: 38860
The solution was as I suspected:
public IEnumerable<KeyValuePair<string, string>> GetAllMembers(string group)
{
var domainContext = new PrincipalContext(ContextType.Domain);
var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, group);
return from m
in groupPrincipal.Members
select new KeyValuePair<string, string>(m.SamAccountName, m.Name);
}
where the SamAccountName
gives the users logon name and the Name
is the actual name
Upvotes: 5
Reputation: 44605
I would read previous similar questions to answer both of your questions, about best practices and about how to read accountname and full name: Get all users from AD domain
anyway, from MS forum:
static void Main(string[] args)
{
string groupName = "Domain Users";
string domainName = "";
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName);
if (grp != null)
{
foreach (Principal p in grp.GetMembers(false))
{
Console.WriteLine(p.SamAccountName + " - " + p.DisplayName);
}
grp.Dispose();
ctx.Dispose();
Console.ReadLine();
}
else
{
Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?");
Console.ReadLine();
}
}
source: Get list of Active Directory users in C#
Upvotes: 0