In this question: Looping through DirectoryEntry or any object hierarchy - C#
The suggested answer for traversing an LDAP tree is to
DirectoryEntry root = new DirectoryEntry(someDN);
DoSomething(root);
function DoSomething(DirectoryEntry de){
// Do some work here against the directory entry
if (de.Children != null) {
foreach (DirectoryEntry child in de.Children) {
DoSomething(child);
}
}
}
My Question is: Do you need to call Dispose() on each child at the end of each iteration? or will the foreach-loop handle the necessary calls to Dispose()? or are they simply not necessary in a foreach-loop (because perhaps the loop re-uses the resources one would otherwise want to Dispose())
Yes you need to call
Dispose
on every child. When you callChildren
property ofDirectoryEntry
, it actually creates newDirectoryEntries
instance. When you enumerate over that instance, it pulls child entries one by one (not all of them at once), and it will notDispose
them (nor anything will reuse them). SinceDirectoryEntry
is basically COM object - it's quite important to dispose it (it hold unmanaged resources). So correct way is something like this: