0

I have a set of objects, each of which has a collection of objects in it (those are obvious from the code below). I want to create a 'dispose' method that goes through, getting rid of all the attachments and then the sections, so I can delete the related files. The objects are used in various spots so the 'using' method isn't appropriate as far as I can see. The below fails (understandably) because the collection has been modified.

// Find files and get names.
foreach (DocumentSection s in this.sections)
{
    foreach (EmailAttachment a in s.SectionAttachments)
    {
        // Get file location, then clear attachment to release file handle.
        filesToDelete.Add(a.TempAttachmentFileLoc);
        s.SectionAttachments.Remove(a);
        a = null;
    }
    this.sections.Remove(s);
    s = null;
}

The reason I'm doing all this is because I want to delete the temp file after use (TempAttachmentFileLoc) but it's in use and can't presently be deleted.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Glinkot
  • 2,924
  • 10
  • 42
  • 67
  • 3
    you don't ask a question..... you've waffled about something, and how you want to solve it. :) – Keith Nicholas Jan 24 '12 at 00:17
  • Iterate backwards + remove last? Or use a Clear method: http://stackoverflow.com/questions/308466/how-to-modify-or-delete-items-from-an-enumerable-collection-while-iterating-thro – Mitch Wheat Jan 24 '12 at 00:19

2 Answers2

1

Why not clear the list after you've enumerated it?

// Find files and get names.
foreach (DocumentSection s in this.sections)
{
    foreach (EmailAttachment a in s.SectionAttachments)
    {
        // Get file location, then clear attachment to release file handle.
        filesToDelete.Add(a.TempAttachmentFileLoc);
        //s.SectionAttachments.Remove(a);  // removed this!
        //a = null;
    }
    s.SessionAttachments.Clear();  // Added this
    //this.sections.Remove(s);  // Removed this
    //s = null;
}
this.sections.Clear();  // Added this

That should do what you're attempting.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • Come to think of it, since you're going to clear the entire `sections` collection. there's no need for the `s.SessionAttachments.Clear()`. Assuming the collection and the document aren't referenced anywhere else, they will be cleaned up on the next garbage collection after the call to `this.sections.Clear()`. – Jim Mischel Jan 24 '12 at 01:32
  • Thanks Jim. I've done this and still have weird file handle issues. Appreciate your effort though, I'm sure this does the disposing without issue. :) – Glinkot Jan 24 '12 at 01:43
0

You don't need to remove the items from the list to Dispose them. Just iterate over your list, and dispose each one in turn. If you want to empty the collection, do it after the loop is complete.

recursive
  • 83,943
  • 34
  • 151
  • 241