Active Directory User Group Membership GroupPrincipal

I am trying to use GroupPrincipal (part of the System.DirectoryServices.AccountManagement namespace) to populate a list of type string, so I can check if the user is a member of an Active Directory group. Here is the edited class that I have written so far:

 public class ActiveDirectoryMembership { private PrincipalContext context = new PrincipalContext(ContextType.Domain, Environment.UserDomainName); private List<string> GroupName {get;set;} public ActiveDirectoryMembership() { //Code snipped - this part returns a list of users populateGroups(); } private void populateGroups() { GroupPrincipal SearchGroup = GroupPrincipal.FindByIdentity(context, "Group Name"); GroupName = new List<string>(); foreach (UserPrincipal p in GroupName.GetMembers()) { GroupName.add(p.SamAccountName); } } 

So where am I mistaken?

Thanks in advance:)

+7
c # active-directory
source share
2 answers

This modification of your code works (I did tests to make sure):

  private static readonly string DomainName = "domaincontrollercomputer.domain.com"; private static readonly string DomainContainer = "DC=DOMAIN,DC=COM"; private static readonly string ADGroupName = "AD Group Name"; private List<string> GroupName {get;set;} private void populateGroups() { using (var ctx = new PrincipalContext(ContextType.Domain, DomainName, DomainContainer)) { using (var grp = GroupPrincipal.FindByIdentity(ctx, ADGroupName)) { GroupName = new List<string>(); foreach (var member in grp.GetMembers()) { GroupName.Add(member.SamAccountName); } } } } 
+4
source share

I think you have a simple typo in your method - you get the main group in SearchGroup (check NULL , btw !!) and then you grab the members of GroupName ??

Try the following:

 private void populateGroups() { GroupPrincipal SearchGroup = GroupPrincipal.FindByIdentity(context, "Group Name"); if(SearchGroup != null) { GroupName = new List<string>(); // call 'GetMembers' on 'SearchGroup' here!! foreach (UserPrincipal p in SearchGroup.GetMembers()) { GroupName.add(p.SamAccountName); } } } 
0
source share