C# Outlook COMException "Item has been moved or deleted"

324 Views Asked by At

When running this loop to delete multiple of the same email I run into this exception. I believe it has to do with the length of oItems losing 1 due to an item being deleted, but it is not updated in the foreach loop.

            //Get the Inbox folder.
            Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            //Get the Items collection in the Inbox folder.
            Outlook.Items oItems = oInbox.Items;

                //loops through all inbox items
                foreach (object item in oItems)
                {
                    //checks to only use MailItems (no MeetingItems etc.)
                    if (item is Outlook.MailItem)
                    {
                        if (item.Subject != null)
                        {
                            if (item.SenderEmailAddress == "[email protected]")
                            {
                                item.Delete();
                            }
                        }
                    }
                }
1

There are 1 best solutions below

1
Dmitry Streblechenko On BEST ANSWER

Do not use "foreach" when modifying a collection by calling Move or Delete.

Use a down "for" loop

for(int i = oItems.Count; i >= 1; i--)
{
  object item = oItems[i];
  ...