Search code examples
c#outlook-addin

Why does (inspector.CurrentItem != null) result in an open file handle that is not closed


If Outlook opens a .msg file and my add-in accesses Microsoft.Office.Interop.Outlook.Inspector.MailItem and then the file is closed. A file handle remains open to the file preventing it from being deleted or renamed until Outlook is shutdown.

Id doesn't matter if the file is saved or not or if I even do anything with the MailItem.

Here is my GetCurrentMailItem() code which reproduces the problem.

    private Outlook.MailItem GetCurrentMailItem()
    {
    Outlook.MailItem mailItem = null;
    Microsoft.Office.Interop.Outlook.Inspector inspector = this.Application.ActiveInspector();

    if (inspector != null && inspector.CurrentItem != null)
        {
            //if (inspector.CurrentItem is Outlook.MailItem)
                //mailItem = inspector.CurrentItem;
        }
        return mailItem;
    }

NOTE: I do not even need to return the CurrentItem, just testing it for NULL is enough to reproduce this.

If I do not do the "inspector.CurrentItem != null" test in this code and just return NULL there is no problem with an open file handle.

Adding an attachment using the standard attachment button doesn't result in this problem.


Solution

  • Of course - inspector.CurrentItem returns a MailItem object. What do you decide to do with it, Outlook does not know and does not care. You decide to rely on the Garbage Collector to release the implicit variable created by the compiler for you.

    Use an explicit variable that you can explicitly release:

    if (inspector != null)
    {
        object item = inspector.CurrentItem;
        if (item != null)
        {
           //blah
           Marshal.ReleaseComObject(item); 
        }
    }