Search code examples
c#asp.netactive-directorydnsdirectoryentry

Get windows group members along with their domain names


I have a windows group called "windgrp" it has three members in it:

  • Administrators
  • testDomain.Administrator
  • user1

I have this code to display the members present in a group:

using (DirectoryEntry groupEntry = 
  new DirectoryEntry("WinNT://./" + userGroupName + ",group"))
{
    foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
    {
        using (DirectoryEntry memberEntry = new DirectoryEntry(member))
        {

            listbox.itms.add(memberentry.name);
        }
    }
}

This gives me the result:

  • Administrator
  • Administrator
  • user

It does not show me to which domain the 2nd entry belongs to.

How can I get the domain?


Solution

  • You need to walk up the hierarchy of objects. So if you have your user, you can start recursion from there up, looking for schema classes that satisfy your search criteria.

    public DirectoryEntry FindDomain(DirectoryEntry memberEntry) 
    {
       if (memberEntry.SchemaClassName.ToLower().Contains("domain") 
          return memberEntry;
    
       if (memberEntry.Parent !=null) 
          return FindDomain(memberEntry.Parent);
    
       return null;
    }