private void AddChildren(TreeNode parent, ADTree tree)
 {
     foreach (ADTree t in tree.ChildOUs)
     {
         TreeNode node = new TreeNode(t.RootOU.Path);
         parent.Nodes.Add(node);
         if (t.ChildOUs.Count > 0)
         {
             AddChildren(node, t);
         }
     }
 }
 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);
                 }
             }
         });
     }));
 }
        private void button1_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();
            string top  = string.Format("LDAP://DC={0}", Domain.GetCurrentDomain().Name.Replace(".", ",DC="));
            ADTree tree = null;

            Task BuildOUStructure = Task.Factory.StartNew(() =>
            {
                tree = new ADTree(top);
            });

            BuildOUStructure.Wait();
            foreach (ADTree t in tree.ChildOUs)
            {
                TreeNode node = new TreeNode(t.RootOU.Path);
                treeView1.Nodes.Add(node);
                if (t.ChildOUs.Count > 0)
                {
                    AddChildren(node, t);
                }
            }
        }