Get Members of an Active Directory Distribution Group


/ Published in: C#
Save to your folder(s)

This is very useful if you need to populate a dropdown.


Copy this code and paste it in your HTML
  1. // Get all users from an Active Directory distribution group
  2. public SortedList GetUsersInGroup(string domain, string group)
  3. {
  4. SortedList groupMemebers = new SortedList();
  5.  
  6. string sam = "";
  7. string fname = "";
  8. string lname = "";
  9. string active = "";
  10.  
  11. DirectoryEntry de = new DirectoryEntry("LDAP://DC=" + domain + ",DC=com");
  12.  
  13. DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=person)");
  14. ds.Filter = "(memberOf=CN=" + group + ",OU=Distribution Groups,DC=" + domain + ",DC=com)";
  15.  
  16. ds.PropertiesToLoad.Add("givenname");
  17. ds.PropertiesToLoad.Add("samaccountname");
  18. ds.PropertiesToLoad.Add("sn");
  19. ds.PropertiesToLoad.Add("useraccountcontrol");
  20.  
  21. foreach (SearchResult sr in ds.FindAll())
  22. {
  23. try
  24. {
  25. sam = sr.Properties["samaccountname"][0].ToString();
  26. fname = sr.Properties["givenname"][0].ToString();
  27. lname = sr.Properties["sn"][0].ToString();
  28. active = sr.Properties["useraccountcontrol"][0].ToString();
  29. }
  30. catch (Exception e)
  31. {
  32. }
  33.  
  34. // don't grab disabled users
  35. if (active.ToString() != "514")
  36. {
  37. groupMemebers.Add(sam.ToString(), (fname.ToString() + " " + lname.ToString()));
  38. }
  39. }
  40.  
  41. return groupMemebers;
  42. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.