Search code examples
.netvb.netoutlookoutlook-2010comexception

COMException when too many outlook files were opened


Short question: how to close outlook items properly after using them?


Code to reproduce the problem:

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

Explanation:
It is possible to copy outlook items (MailItem, DocumentItem, PostItem, basically any item) into my application. To achieve this, I iterate over the selected items of the active outlook window. It works fine, but when more than 250 (it might be a different number depending on configuration) items are selected, a COMExeption is thrown:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in Microsoft.VisualBasic.dll

Additional information: Your server administrator has limited the number of items you can open simultaneously. Try closing messages you have opened or removing attachments and images from unsent messages you are composing.

I tried to close the items when I don't need them any more, but it does not seem like it does anything.


Other questions about the same error
I know about this other question that is about the same error, but I already follow the advise of the first two answers and the third, accepted (and last) answer doesn't fit into my context


Solution

  • Thanks to @Dmitry Streblechenko, who pointed out that the Selection collection holds references to the items, I found a solution. It removes the items from Selection after processing them and renews the collection at every exception.

    Here is the code:

    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