Question

I have created an Active Directory object browser using the WPF TreeView element, but I want to only add OUs to my tree. I feel like I am very close, here is my code thus far for my Item.Expanded event handler. This all works, but it adds every object, whereas I want to filter out non-OU objects:

 private void item_Expanded(object sender, RoutedEventArgs e)
    {
        TreeViewItem item = (TreeViewItem)e.OriginalSource;
        item.Items.Clear();

        DirectoryEntry de;
        if (item.Tag is Domain)
        {
            Domain dom = (Domain)item.Tag;
            de = dom.GetDirectoryEntry();
        }
        else
        {
            de = (DirectoryEntry)item.Tag;
        }

        try
        {
            foreach (DirectoryEntry dirEntry in de.Children)
            {
                TreeViewItem newItem = new TreeViewItem();
                newItem.Tag = dirEntry;
                newItem.Header = dirEntry.Name;
                newItem.Items.Add("*");
            }
        }

        catch (Exception ex)
        {
            //Exception!
            textBox.Text = ex.ToString();
        }
    }

I had something like

if (dirEntry.Properties["objectClass"].Value.ToString() == "organizationalUnit")

but that didn't work (objectClass is an array of values, so comparing to a string didn't work).

Was it helpful?

Solution 2

if (dirEntry.Properties["objectClass"].Contains("organizationalUnit"))

Got me what I wanted. Hope this helps someone else!

OTHER TIPS

The more general way is to use DirectorySearcher:

DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(objectClass=organizationalUnit)";
ds.SearchScope = SearchScope.OneLevel;
foreach (SearchResult sr in ds.FindAll())
{
    DirectoryEntry dirEntry = sr.GetDirectoryEntry();
    //your code here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top