We Recommend

Accelerated C# 2008 Accelerated C# 2008
This book is both a rapid tutorial and a permanent reference. You’ll quickly master C# syntax while learning how the CLR simplifies many programming tasks. You’ll also learn best practices that ensure your code will be efficient, reusable, and robust. Why spend months or years discovering the best ways to design and code C# when this book will show you how to do things the right way, right from the start?


Posted By

ecavazos on 01/18/08


Tagged

directory active


Versions (?)


Get Members of an Active Directory Distribution Group


Published in: C# 


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

  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 

You need to login to post a comment.