【问题标题】:C# Outlook COMException "Item has been moved or deleted"C# Outlook COMException“项目已被移动或删除”
【发布时间】:2021-09-23 22:35:39
【问题描述】:

运行此循环以删除多个相同的电子邮件时,我遇到了此异常。我认为这与 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();
                            }
                        }
                    }
                }

【问题讨论】:

  • 从循环中的集合中删除项目时,从长度 1 循环到 0 总是安全的。
  • 请记住,OOM 中的所有集合都是基于 1,而不是 0。

标签: c# outlook comexception


【解决方案1】:

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

使用向下的“for”循环

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

【讨论】:

  • 我之前还没有听说过向下循环。谢谢德米特里!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 2015-08-24
相关资源
最近更新 更多