user1799939
user1799939

Reputation:

Active Directory group enumeration

I am querying the corporate LDAP list with the following code. The problem is it writes out the full string. Is there an easy way to just write out the group name, apart from string parsing?

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

public class Test
{
    public static void Main()
    {
        string userName = "USER";

        DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://dc=ABC,dc=com");

        DirectorySearcher search = new DirectorySearcher();

        search.Filter = String.Format("(cn={0})", userName);
        search.PropertiesToLoad.Add("memberOf");

        List<string> groupsList = new List<string>();

        SearchResult result = search.FindOne();
        if (result != null)
        {
            int groupCount = result.Properties["memberOf"].Count;

            for (int counter = 0; counter < groupCount; counter++)
            {
                groupsList.Add((string)result.Properties["memberOf"][counter]);
            }
        }

        List<string> list = new List<string>();
        list = groupsList.ToList();

        for (int i = 0; i < list.Count; i++)
        {
            Console.WriteLine(list[i]);
        }

    }

}

Upvotes: 4

Views: 567

Answers (1)

Luiz Angelo
Luiz Angelo

Reputation: 336

I think the solution is easier than that.

You are trying to find the user's groups, right?

private void button1_Click(object sender, EventArgs e)
{
   List<string> userGroups = new List<string>();
   PrincipalContext LdapContext = new PrincipalContext(ContextType.Domain, domainName);
   UserPrincipal user = UserPrincipal.FindByIdentity(LdapContext, userName);

   foreach (var group in user.GetGroups())
   {
       userGroups.Add(group.Name);
   }
}

Upvotes: 2

Related Questions