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

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

当运行宁此循环删除多个相同的电子邮件时,我运行进入此异常。我相信这与 oItems 由于删除项目而丢失 1 的长度有关,但它不会在 foreach 循环中更新。

            //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 == "no-reply@virginpulse.com")
                            {
                                item.Delete();
                            }
                        }
                    }
                }

通过调用 MoveDelete 修改集合时不要使用“foreach”。

使用向下“for”循环

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