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,240 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:agarwalrahul
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
Independent Software Vendors: 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!

 
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

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

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

Creating and Managing Databases with phpMyAdmin in cPanel.
This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
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…

679 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