Breeze Breeze - 7 months ago 45
Vb.net Question

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

Answer

Thanks to @Dmitry Streblechenko, who pointed out that the Selection collection holds references to the items, I found a solution. It removes 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

While True
    Try
        For i As Integer = 1 To olSelection.Count
            Dim olItem As Object = olSelection(i)
            Dim sSubject As String = olItem.Subject
            olExplorer.RemoveFromSelection(olItem)
        Next
        Exit While
    Catch ex As Exception
        olSelection = olExplorer.Selection
    End Try
End While