Click here to Skip to main content
15,909,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would like to get all OUs in a domain in hierarchical order and bind it to tree view in MVC.

What I have tried:

I tried below code but it returns empty.
C#
Domain domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, "domainname", "username", "password"));
Forest forest = domain.Forest;
DomainCollection domains = forest.Domains;

But if I use this code I get list of OUs but not how I want.
C#
List<string> lstName = new List<string>();
            DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://DC=domainname,DC=com", "username", "password");
            DirectorySearcher oDirectorySearcher = new DirectorySearcher(directoryEntry,"(objectCategory=organizationalUnit)", null);

            SearchResultCollection oSearchResultCollection = oDirectorySearcher.FindAll();
            foreach (SearchResult item in oSearchResultCollection)
            {
                string name = item.Properties["name"][0].ToString();
                lstName.Add(name);
            }


Can anyone help?

Thanks
Posted
Updated 15-Nov-16 2:35am
v2
Comments
Michael_Davies 15-Nov-16 6:36am    
Are you putting in a real domain name and usernames and passwords?
Member 12586674 15-Nov-16 6:44am    
Yes. I get list of all OUs in List<string> format.
But I want it in hierarchical manner for tree view.
Nelek 15-Nov-16 6:51am    
doing visible the users and the passwords? what for?
Member 12586674 15-Nov-16 6:53am    
Sorry but didn't understand.
Nelek 15-Nov-16 7:04am    
Nevermind...

1 solution

There is no search function in AD, or pretty much any system for that matter, that will return a hierarchy. You have to build it yourself.

Get the top level items you want in the root of your TreeView. Add those items to and add a dummy item to each of them so you get the little "+" sign next to them. When the use clicks the "+" to expand that node, you handle the BeforeExpand event. In there, you remove the dummy node, do another query to get the child items you want from that node and add them to the node being expanded. Again, populate thee child nodes with a single dummy node to get the "+" to to them.

That's all there is to it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900