打开太多Outlook文件时出现COMException

时间:2016-04-28 07:09:50

标签: .net vb.net outlook outlook-2010 comexception

简短问题:如何在使用后正确关闭Outlook项目?

代码重现问题:

Dim olApp As New Microsoft.Office.Interop.Outlook.Application
Dim olSelection As Microsoft.Office.Interop.Outlook.Selection = olApp.ActiveExplorer.Selection

For i As Integer = 1 To olSelection.Count   'Outlook starts counting at 1
    Dim olItem As Object = olSelection(i)
    Dim sSubject As String = olItem.Subject
    olItem.Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olDiscard)
    Runtime.InteropServices.Marshal.ReleaseComObject(olItem)
Next

解释
可以将Outlook项目(MailItemDocumentItemPostItem,基本上任何项目)复制到我的应用程序中。为此,我迭代活动Outlook窗口的选定项目。 它工作正常,但如果选择的项目超过250(可能是不同的数字,具体取决于配置),则会抛出COMExeption

  

未处理的类型' System.Runtime.InteropServices.COMException'发生在Microsoft.VisualBasic.dll

     

其他信息:您的服务器管理员限制了您可以同时打开的项目数。尝试关闭已打开的邮件,或从正在撰写的未发送邮件中删除附件和图像。

当我不再需要它时,我试图关闭这些物品,但它似乎没有做任何事情。

有关同一错误的其他问题
我知道关于同一错误的this其他问题,但我已经遵循前两个答案的建议而第三个,接受的(和最后一个)答案不适合我的上下文

2 个答案:

答案 0 :(得分:0)

您无能为力 - 选择集合本身包含对项目的引用。尝试打开缓存模式。

答案 1 :(得分:0)

感谢@Dmitry Streblechenko,他指出Selection集合包含对项目的引用,我找到了解决方案。它在处理后从Selection中删除项目,并在每个例外更新集合。

以下是代码:

Dim olApp As New Microsoft.Office.Interop.Outlook.Application
Dim olExplorer As Microsoft.Office.Interop.Outlook.Explorer = olApp.ActiveExplorer
Dim olSelection As Microsoft.Office.Interop.Outlook.Selection = olExplorer.Selection

Dim items as New List(Of Object)

While True
    Try
        For i As Integer = 1 To olSelection.Count
            Dim olItem As Object = olSelection(i)
            Dim sSubject As String = olItem.Subject
            olItem.Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olDiscard)
            olExplorer.RemoveFromSelection(olItem)
            Runtime.InteropServices.Marshal.ReleaseComObject(olItem)
        Next
        Exit While
    Catch ex As Exception
        Runtime.InteropServices.Marshal.ReleaseComObject(olSelection)
        olSelection = olExplorer.Selection
    End Try
End While