Joseph Michael Pesch
VP Programming

C# Code to Get AD Members of a Security Group

by 15. September 2011 09:57

This method will accept a domain name and security group name and return all the AD members of that group.

using System.Collections.Generic;
using System.DirectoryServices;

namespace AdReader
{
  class Program
  {
    static void Main(string[] args)
    {
      List users = GetGroupMembers("domainname.com", "security group name");
      foreach (DirectoryEntry user in users)
      {
        System.Diagnostics.Debug.WriteLine(user.Name.Replace("CN=", ""));
      }
    }
    /// Gets a list of members in the specified group.        
    public static List GetGroupMembers(string domain, string groupName)
    {
      List users = new List();
      string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "group", groupName); // principal);            
      string[] properties = new string[] { "fullname" };
      DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
      DirectorySearcher searcher = new DirectorySearcher(adRoot);
      searcher.SearchScope = SearchScope.Subtree;
      searcher.ReferralChasing = ReferralChasingOption.All;
      searcher.PropertiesToLoad.AddRange(properties);
      searcher.Filter = filter;
      SearchResult result = searcher.FindOne();
      if (result != null)
      {
        DirectoryEntry directoryEntry = result.GetDirectoryEntry();
        foreach (object dn in directoryEntry.Properties["member"])
        {
          DirectoryEntry member = new DirectoryEntry("LDAP://" + dn);
          //Add users from other groups within this group (only go 1 level deep).      
          if (!IsGroup(member))
          {
            users.Add(member);
          }
        }
      }
      return users;
    }
    /// Determine whether the object is a group.        
    private static bool IsGroup(DirectoryEntry de)
    {
      return de.Properties["objectClass"][1].ToString() == "group";
    }
  }
}

Tags:

C#

Comments are closed