First, you should search for all entries (instead of only OUs) and use Searcher.FindOne().GetDirectoryEntry().Children
to get the results instead of ADentry.Children
.
When specifying all entries ((objectClass=*)
), the first returned result is always the root domain.
Second, you should filter the result's SchemaClassName
to remove entries that you are not interested in.
So for example,
DirectoryEntry ADentry = new DirectoryEntry("LDAP://10.36.6.163/DC=server,DC=local", AD.LDAPUser, AD.Password, AuthenticationTypes.Secure);
DirectorySearcher Searcher = new DirectorySearcher(ADentry);
Searcher.Filter = ("(objectClass=*)"); // Search all.
// The first item in the results is always the domain. Therefore, we just get that and retrieve its children.
foreach (DirectoryEntry entry in Searcher.FindOne().GetDirectoryEntry().Children)
{
if (ShouldAddNode(entry.SchemaClassName))
TreeView1.Nodes.Add(GetChildNode(entry));
}
The GetChildNode()
method is defined as follows:
private TreeNode GetChildNode(DirectoryEntry entry)
{
TreeNode node = new TreeNode(entry.Name.Substring(entry.Name.IndexOf('=') + 1));
foreach (DirectoryEntry childEntry in entry.Children)
{
if (ShouldAddNode(childEntry.SchemaClassName))
node.Nodes.Add(GetChildNode(childEntry));
}
return node;
}
Note: The ShouldAddNode()
method is used to filter only useful node types, such as "organizationalUnit"
. Other possibly useful node types for you are "group"
, "computer"
, "user"
, "contact"
.