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,230 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
 
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
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…

707 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

12 Experts available now in Live!

Get 1:1 Help Now