Solved

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

Posted on 2011-09-30
7
710 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Office 365 Training for IT Pros

Learn how to provision Office 365 tenants, synchronize your on-premise Active Directory, and implement Single Sign-On.

 
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This article demonstrates probably the easiest way to configure domain-wide tier isolation within Active Directory. If you do not know tier isolation read https://technet.microsoft.com/en-us/windows-server-docs/security/securing-privileged-access/s…
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

738 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