Solved

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

Posted on 2011-09-30
7
519 Views
Last Modified: 2016-11-30
What would be the easiest and quick way to find all users for a particular group in Active directory using C# code ?
0
Comment
Question by:Barnum
7 Comments
 
LVL 40

Accepted Solution

by:
Kyle Abrahams earned 500 total points
ID: 36892750
0
 

Author Comment

by:Barnum
ID: 36892950

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
 
LVL 2

Expert Comment

by:AJRDev
ID: 36893060
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
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 36900345
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
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 36900353
...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
 

Author Closing Comment

by:Barnum
ID: 36919634
Partial solution.
0
 

Expert Comment

by:Howard Rothenburg
ID: 41907852
//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

Join & Write a Comment

Companies that have implemented Microsoft’s Active Directory need to ensure that the Active Directory is configured and operating properly. If there are issues found and not resolved, it eventually leads the components to fail or stop working and fi…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now