Shesha
Shesha

Reputation: 2007

Get user names of Active Directory group in c#

I need to get user details of a particular Active Directory group. I am using this code:

var result = grpResponse.Entries[0];

if (result.Attributes["member"] != null)
{
    for (var i = 0; i < result.Attributes["member"].Count; i++)
    {
          var filter = result.Attributes["member"][i].ToString();

          var query = "(&(objectClass=user)(" + filter + "))"; // Here I need username to use like cn=username

          var userRequest = new SearchRequest(distinguishedName, query,
                                    SearchScope.Subtree);

In filter I am getting something like

CN=Name,OU=something,DC=example

How can I take this cn value i.e user name alone?

Upvotes: 2

Views: 3657

Answers (2)

andrewcw
andrewcw

Reputation: 1

The below is exactly what I needed.

The OuString you use like ours may have has multiple parts - both OU & DC

bstring OUString = "OU=Groups,OU=Accounts,DC=nw,DC=nos,DC=ourcompanyName,DC=com" ;

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, OUString))

Upvotes: 0

marc_s
marc_s

Reputation: 754220

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace.

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context - limit to the OU you're interested in
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, "OU=YourOU,DC=YourCompany,DC=Com"))
{
    // find the group in question
    GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

    // if found....
    if (group != null)
    {
       // iterate over the group's members
       foreach (Principal p in group.GetMembers())
       {
           Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);

           // do whatever else you need to do to those members
       }
    }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

Read more about it here:

Upvotes: 3

Related Questions