I know this thread is a bit old, but I recently created a more efficient way to maneuver through DirectoryEntries than DirectorySearcher provides and would like to share, as this was the best result on Google. In this example, the OU structure is replicated based on the initial given starting point.
The DN path passed to the first constructor must be in the format "LDAP: // OU = StartingOU, DC = test, DC = com"
using System.DirectoryServices; using System.Threading.Tasks; public class ADTree { DirectoryEntry rootOU = null; string rootDN = string.Empty; List<ADTree> childOUs = new List<ADTree>(); public DirectoryEntry RootOU { get { return rootOU; } set { rootOU = value; } } public string RootDN { get { return rootDN; } set { rootDN = value; } } public List<ADTree> ChildOUs { get { return childOUs; } set { childOUs = value; } } public ADTree(string dn) { RootOU = new DirectoryEntry(dn); RootDN = dn; BuildADTree().Wait(); } public ADTree(DirectoryEntry root) { RootOU = root; RootDN = root.Path; BuildADTree().Wait(); } private Task BuildADTree() { return Task.Factory.StartNew(() => { object locker = new object(); Parallel.ForEach(RootOU.Children.Cast<DirectoryEntry>().AsEnumerable(), child => { if (child.SchemaClassname.Equals("organizationalUnit")) { ADTree ChildTree = new ADTree(child); lock (locker) { ChildOUs.Add(ChildTree); } } }); }); } }
To create everything you need to do the following:
ADTree Root = null; Task BuildOUStructure = Task.Factory.StartNew(() => { ADTree = new ADTree("LDAP://ou=test,dc=lab,dc=net"); }); BuildOUStructure.Wait();
Jaime still
source share