Share via


Get all users from an Active Directory Group

Question

Wednesday, August 18, 2010 12:54 PM

Hi,

I want to build a windows form, with a textbox one button and a listbox.

I want to provide the AD group name on text box, press the button and display all the users from that group to the listbox.

I just need the code to get the users from AD based on the group name.

Thanks.

All replies (3)

Wednesday, August 18, 2010 1:38 PM âś…Answered | 1 vote

public SortedList GetUsersInGroup(string domain, string group)

{

    SortedList groupMemebers = new SortedList();

 

    string sam = "";

    string fname = "";

    string lname = "";

    string active = "";

 

    DirectoryEntry de = new DirectoryEntry("LDAP://DC=" + domain + ",DC=com");

 

    DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=person)");

    ds.Filter = "(memberOf=CN=" + group + ",OU=Distribution Groups,DC=" + domain + ",DC=com)";

 

    ds.PropertiesToLoad.Add("givenname");

    ds.PropertiesToLoad.Add("samaccountname");

    ds.PropertiesToLoad.Add("sn");

    ds.PropertiesToLoad.Add("useraccountcontrol");

 

    foreach (SearchResult sr in ds.FindAll())

    {

        try

        {

            sam = sr.Properties["samaccountname"][0].ToString();

            fname = sr.Properties["givenname"][0].ToString();

            lname = sr.Properties["sn"][0].ToString();

            active = sr.Properties["useraccountcontrol"][0].ToString();

        }

        catch (Exception e)

        {

        }

 

        // don't grab disabled users

        if (active.ToString() != "514")

        {

            groupMemebers.Add(sam.ToString(), (fname.ToString() + " " + lname.ToString()));

        }

    }

 

    return groupMemebers;

}


Thursday, August 19, 2010 4:33 PM

Thank you very much!


Sunday, August 22, 2010 4:01 PM

Hi again,

I have tried your example, works fine. Can you tell me how can I search for users from a specific group based on solution you gave to me ?

 

Br,