How to get all users for a particular group in Active directory using C#?

What would be the easiest and quick way to find all users for a particular group in Active directory using C# code ?
BarnumAsked:
Who is Participating?
 
BarnumAuthor Commented:

Thanks for quick response .
I tried that solution earlier but did`t work for me.

Here is my verion of implementation.
It does not return users for particular group of active directory. Any idea??

 public SearchResultCollection GetActiveDirectoryUserEntries(string activeDirectoryGroupName)
        {
            String ldapFilter = "(&(objectCategory=person)(memberOf=" + ActiveDirectoryEntry + "))";

            // Get the DirectoryEntry of the current domain. Assuming authentication.
            DirectoryEntry adDomain = new DirectoryEntry();
            // Construct the Directory Searcher
            DirectorySearcher adSearch = new DirectorySearcher(adDomain, ldapFilter);
             adSearch.PageSize = 1000;
            // Request some properties for the Result Collection
            adSearch.PropertiesToLoad.AddRange(new String[] { "name", "distinguishedName" });
            // Create the result set
            SearchResultCollection adSearchResults = adSearch.FindAll();
            // Loop through the results to verify the user`s details
            foreach (SearchResult adSearchResult in adSearchResults)
            {
                // Write the name and distinguished name to the console.
                string name = adSearchResult.Properties["name"][0].ToString();
                string distinguishedname = adSearchResult.Properties["distinguishedname"][0].ToString();
            }
            return adSearchResults;
        }
0
 
AJRDevCommented:
As a first cut I would try something like this:

public class ActiveDirectoryUtils
{
    public DataTable GetUsersForGroup(string groupName, string adAdminUser, string adAdminPassword)
    {
        DirectoryEntry deSearchRoot = new DirectoryEntry("GC://forestname");
        DirectorySearcher directorySearcher = new DirectorySearcher();
        DataTable dtUsers = new DataTable();

        // Create the result table schema.
        dtUsers.Columns.Add("UserName");
        dtUsers.Columns.Add("DisplayName");
        dtUsers.Columns.Add("EmailAddress");

        // Set the search filter.
        directorySearcher.SearchRoot = deSearchRoot;
        directorySearcher.Filter = "(&(objectClass=group)(cn=" + groupName + "))";

        // Get the group result.
        SearchResult searchResult = directorySearcher.FindOne();

        if(searchResult != null)
        {
            // Get the group object so we can get the list of members.
            DirectoryEntry deGroup = new DirectoryEntry(searchResult.Path, adAdminUser, adAdminPassword, AuthenticationTypes.Secure);

            // Get the group's property collection.
            System.DirectoryServices.PropertyCollection propertyCollection = deGroup.Properties;
            int propertyCount = propertyCollection["member"].Count;

            // Iterate the property collection and pull out the user details.
            for(int j = 0; j < propertyCount; j++)
            {
                DirectoryEntry deUser = new DirectoryEntry(deGroup.Path + "/" + propertyCollection["member"][j].ToString(), adAdminUser, adAdminPassword, AuthenticationTypes.Secure);

                DataRow rowUser = dtUsers.NewRow();

                rowUser["UserName"] = GetValidProperty(deUser, "cn");
                rowUser["DisplayName"] = GetValidProperty(deUser, "givenName") + " " + GetValidProperty(deUser, "sn");
                rowUser["EmailAddress"] = GetValidProperty(deUser, "mail");

                dtUsers.Rows.Add(rowUser);
                deUser.Close();
            }
            deGroup.Close();
            deSearchRoot.Close();
        }

        return dtUsers;
    }

    private string GetValidProperty(DirectoryEntry directoryEntry, string propertyName)
    {
        if(directoryEntry.Properties.Contains(propertyName))
        {
            return directoryEntry.Properties[propertyName][0].ToString();
        }
        else
        {
            return string.Empty;
        }
    }
}
0
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

 
Todd GerbertIT ConsultantCommented:
I assume you're talking about security groups here, and not organizational units - both can contain users, but the two are distinctly different types of entities.

One way is to get the DirectoryEntry for the group, and then enumerate it's "member" property:
using System;
using System.Linq;
using System.DirectoryServices;

class Program
{
	static void Main(string[] args)
	{
		// Get the 
		DirectoryEntry domainAdmins = new DirectoryEntry("LDAP://CN=Domain Admins,CN=Users,DC=SUSSMANAUTO,DC=com");

		Console.WriteLine("Members of {0}:", domainAdmins.Properties["distinguishedName"][0]);

		// Loop through the members
		foreach (string userPath in domainAdmins.Properties["member"])
		{
			// Get a directoryentry object for this user
			DirectoryEntry user = new DirectoryEntry(String.Format("LDAP://{0}", userPath));

			// Show the display name
			Console.WriteLine("\t{0}", user.Properties["name"][0]);
		}

		Console.ReadKey();
	}
}

Open in new window


Another option is to use an LDAP query to search all users whose "memberOf" attribute contains the group in question:
using System;
using System.Linq;
using System.DirectoryServices;

class Program
{
	static void Main(string[] args)
	{
		// Where to start search from
		DirectoryEntry searchRoot = new DirectoryEntry("LDAP://DC=sussmanauto,DC=com");
		
		// Group we're listing members of
		string group = "CN=Domain Admins,CN=Users,DC=SUSSMANAUTO,DC=com";
		
		// Search filter
		string filter = String.Format("(&(objectClass=user)(memberOf={0}))", group);
		
		// Create a directory searcher
		DirectorySearcher searcher = new DirectorySearcher(searchRoot, filter, new string[] { "name" }, SearchScope.Subtree);

		// Get search results
		SearchResultCollection results = searcher.FindAll();

		Console.WriteLine("Members of {0}:", group);

		foreach (SearchResult user in results)
			Console.WriteLine("\t{0}", user.Properties["name"][0]);

		Console.ReadKey();
	}
}

Open in new window



0
 
Todd GerbertIT ConsultantCommented:
...although note that groups can be nested so you might not get all the users of a group unless you also enumerate the groups contained in the group.
0
 
BarnumAuthor Commented:
Partial solution.
0
 
Howard RothenburgCommented:
//Search for Group and list group members
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices.AccountManagement;

namespace ExportActiveDirectoryGroupsUsers
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args == null)
            {
                Console.WriteLine("args is null, useage: ExportActiveDirectoryGroupsUsers OutputPath"); // Check for null array
            }
            else
            {
                Console.Write("args length is ");
                Console.WriteLine(args.Length); // Write array length
                for (int i = 0; i < args.Length; i++) // Loop through array
                {
                    string argument = args[i];
                    Console.Write("args index ");
                    Console.Write(i); // Write index
                    Console.Write(" is [");
                    Console.Write(argument); // Write string
                    Console.WriteLine("]");
                }
                try
                {
                    using (var ServerContext = new PrincipalContext(ContextType.Domain, ServerAddress, Username, Password))
                    {
                        /// define a "query-by-example" principal - here, we search for a GroupPrincipal 
                        GroupPrincipal qbeGroup = new GroupPrincipal(ServerContext, args[0]);

                        // create your principal searcher passing in the QBE principal    
                        PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

                        // find all matches
                        foreach (var found in srch.FindAll())
                        {
                            GroupPrincipal foundGroup = found as GroupPrincipal;

                            if (foundGroup != null)
                            {
                                // iterate over members
                                foreach (Principal p in foundGroup.GetMembers())
                                {
                                    Console.WriteLine("{0}|{1}", foundGroup.Name, p.DisplayName);
                                    // do whatever you need to do to those members
                                }
                            }

                        }
                    }
                    //Console.WriteLine("end");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Something wrong happened in the AD Query module: " + ex.ToString());
                }
                Console.ReadLine();
            }
        }
    }
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.