Problems deleting emails in a loop.

Jun 18, 2008 at 2:27 PM
Edited Jun 18, 2008 at 2:28 PM
This example doesn't work more than one time

foreach (IMAPMessage msg in client.Folders["INBOX"].Messages)
{
    //Some logic here when done, delete the message.
    IMAPFolder folder = msg.Folder;
    folder.DeleteMessage(msg);
}

When it now starts fetching the msg after with I get this exception:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Collections.Generic.List`1.Enumerator.MoveNext()

I understand that the client.Folders["INBOX"].Messages collection gets modified, but is there someway I can delete messages one by one when I'm done with them?


Coordinator
Jun 18, 2008 at 3:29 PM
Generally what you need to do in this case is create a temporary list and during your main loop, add the messages that should be deleted to this list, and then once the main loop finishes, you can iterate through the temp list, removing the items from the main collection safely. Here is an example:

List<IMAPMessage> msgsToDelete = new List<IMAPMessage>();

foreach (IMAPMessage msg in client.Folders["INBOX"].Messages)
{
     // logic goes here
     msgsToDelete.Add(msg);
}

foreach (IMAPMessage msg in msgsToDelete)
{
       msg.Folder.DeleteMessage(msg);
}

Because we are no longer iterating through the message collection of the folder, it is now safe to remove messages from it.

Let me know if this solves your issue.
Jason
Jun 19, 2008 at 10:54 AM
Thanks, that worked perfectly :)