Solved

How do I get a list of members in a particular Active Directory group in C#.NET

Posted on 2011-03-06
9
1,247 Views
Last Modified: 2013-12-24
I try and try. I can't find anything working for me. I simply want, when a domain user goes to the www page (ASP.NET and C#.NET), gets a list of members of a particiular group. Any hints, code examples?

IIS is on Windows Server 2003 SP2, LDAP is on Windows Server 2008 R2

Pls help!
0
Comment
Question by:spandor
[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
9 Comments
 
LVL 16

Expert Comment

by:Postmaster
ID: 35048251
Here is the LDIFDE command (LDAP query).

I am not a C# coder - but it may help.

Say your domain is DomainName.Domain.Com
The container is ContainerName

ldifde -f D:\ldif_grpexport.ldf -d "OU=ContainerName,OU=DomainName,DC=Domain,DC=Com" -r "(&(objectCategory=group)(displayName=name-of-group))" -l "DN,objectClass,cn,displayName"
0
 
LVL 13

Expert Comment

by:Rahul Agarwal
ID: 35052114
Use Code:

using System.DirectoryServices;

ArrayList GetADGroupUsers(string groupName)
{    
   SearchResult result;
   DirectorySearcher search = new DirectorySearcher();
   search.Filter = String.Format("(cn={0})", groupName);
   search.PropertiesToLoad.Add("member");
   result = search.FindOne();

   ArrayList userNames = new ArrayList();
   if (result != null)
   {
       for (int counter = 0; counter < 
          result.Properties["member"].Count; counter++)
       {
           string user = (string)result.Properties["member"][counter];
               userNames.Add(user);
       }
   }
   return userNames;
}

Reference :

http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx
0
 

Author Comment

by:spandor
ID: 35053760
I tried this one and it didnt work. Maybe becouse it is from 2005 and I use Framework 4.0.
0
Get MongoDB database support online, now!

At Percona’s web store you can order your MongoDB database support needs in minutes. No hassles, no fuss, just pick and click. Pay online with a credit card. Handle your MongoDB database support now!

 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35059214
Are you referring to a Security Group, like "Domain Admins", or an Organizational Unit (i.e. the containers in the tree, on the left, when viewing in Active Directory Users & Computers)?  There are distinctly different things, and the code will be different for each.
0
 

Author Comment

by:spandor
ID: 35059373
tgerbert,

Yes, im talking about security groups. I setup a new security group which is a role in my app. In one case I need to check if user logged to his computer attached to the domain is in the group and also I need to list members from this group.
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35061061
Here's a simple console application example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.Collections;

namespace ConsoleApplication1
{
	class Program
	{
		static void Main(string[] args)
		{
			string[] users = GetGroupMembers(Environment.UserDomainName, "Domain Admins");

			foreach (string user in users)
				Console.WriteLine(user);

			Console.ReadKey();
		}

		static string[] GetGroupMembers(string DomainName, string GroupName)
		{
			List<string> members = new List<string>();

			// Get the group's directory entry
			using (DirectoryEntry group = new DirectoryEntry(String.Format("WinNT://{0}/{1},group", DomainName, GroupName)))
			{

				// Add members' names to members list
				foreach (object member in (IEnumerable)group.Invoke("Members"))
				{
					using (DirectoryEntry memberEntry = new DirectoryEntry(member))
					{
						members.Add(memberEntry.Name);
					}
				}
			}

			return members.ToArray();
		}
	}
}

Open in new window

0
 

Author Comment

by:spandor
ID: 35066972
Is there a method to get a user accout attributes like Name, Surname, Email etc. ?
0
 
LVL 15

Accepted Solution

by:
angus_young_acdc earned 500 total points
ID: 35071030
The following code will give you various details.  If you put a break point on the results you can see a list of all properties (if you comment out all of the search.PropertiesToLoad) that are available to you.
DirectorySearcher search = new DirectorySearcher(domain);
            search.Filter = "(SAMAccountName=" + user + ")";
            search.PropertiesToLoad.Add("alias");
            search.PropertiesToLoad.Add("memberOf");
            search.PropertiesToLoad.Add("mail");
            search.PropertiesToLoad.Add("physicalDeliveryOfficeName");
            search.PropertiesToLoad.Add("cn"); // surname
            search.PropertiesToLoad.Add("sn"); // surname
            SearchResultCollection results = search.FindAll();
            if (results != null)
            {
                foreach (SearchResult result in results)
                {
                    foreach (ResultPropertyValueCollection property in result.Properties.Values)
                    {
                        foreach (object obj in property)
                        {
                            lstGroups.Items.Add(obj.ToString());
                        }
                    }
                }
            }

Open in new window

0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 35071228
>> Is there a method to get a user accout attributes like Name, Surname, Email etc. ?
Do you mean you want to get these details while listing the members of a group? Or separately on a user-by-user basis?
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

This post contains step-by-step instructions for setting up alerting in Percona Monitoring and Management (PMM) using Grafana.
In this series, we will discuss common questions received as a database Solutions Engineer at Percona. In this role, we speak with a wide array of MySQL and MongoDB users responsible for both extremely large and complex environments to smaller singl…
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

636 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