Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2011-03-06
9
Medium Priority
?
1,278 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
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
Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

 
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 2000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

In this blog post, we’ll look at how ClickHouse performs in a general analytical workload using the star schema benchmark test.
This article shows how to get a list of available printers for display in a drop-down list, and then to use the selected printer to print an Access report or a Word document filled with Access data, using different syntax as needed for working with …
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…
Suggested Courses

876 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