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.
Why not clear the list after you've enumerated it?
That should do what you're attempting.