Get members from given Active Directory group using LDAP filters


You have to add System.DirectoryServices.dll as a reference to your project. If you cannot find it under the .NET tab on the 'Add reference' dialog, you have to browse it from the C:\Windows\Microsoft.NET\framework\vX.Y\ path.

public List<string> GetAllUsersFromGroup(string domain, string group)
{
    List<string> retVal = new List<string>();
    DirectoryEntry entry = new DirectoryEntry(String.Concat("LDAP://", domain));
    DirectorySearcher searcher = new DirectorySearcher("(&(objectCategory=group)(cn=" + group + "))");
    searcher.SearchRoot = entry;
    searcher.SearchScope = SearchScope.Subtree;
    SearchResult result = searcher.FindOne();
    foreach (string member in result.Properties["member"])
    {
        DirectoryEntry de = new DirectoryEntry(String.Concat("LDAP://", domain, "/", member.ToString()));
        if (de.Properties["objectClass"].Contains("user") && de.Properties["cn"].Count > 0)
        {
            retVal.Add(de.Properties["cn"][0].ToString());
        }
    }
    return retVal;
}
Posted on 17:55 by csharper and filed under , , , , | 2 Comments »

2 comments:

Samuel said... @ 16 January 2013 at 19:12

Finally, a solution that works for me.

Thank you very much.

Amin said... @ 21 August 2015 at 16:55

thank you so much :)

Post a Comment