Search code examples
c#.netactive-directorydispose

DirectoryEntry.Children and Dispose


I'm not sure, how to free DirectoryEntry object, when I worked with it's children. Do I need to free all childs aтd then free parent or just free parent?

For example,

using(DirectoryEntry entry = new DirectoryEntry())
{
    foreach (DirectoryEntry childEntry in entry.Children)
    {
        ....
    }   
}

Is it enough?

Or need additional code such as

using(DirectoryEntry entry = new DirectoryEntry())
{
    foreach (DirectoryEntry childEntry in entry.Children)
    {
        using(childEntry)
        {
            ...
        }
    }   
}

?


Solution

  • You have to free every enumerated child.

    Moreover, you should note, that DirectoryEntry.Children returns newly created object every time you access its getter. This is disgustingly, because it is a rough violation of MS own guidelines (DirectoryEntry.Children must be a method), but it is true.

    So:

    • every time you enumerate children, you get new instances;
    • parent entry knows nothing about created instances of enumerator, and child entries, created by enumerator.