Search code examples
c#outlook-addin

Exception : "The operation cannot be performed because the message has been changed."


I have code:

public void ExportEmail(Microsoft.Office.Core.IRibbonControl control)
{
   MailItem mailItem = this.extractor.ExtractMailItem(control);
   mailItem.MessageClass = "Bla bla";
   mailItem.Save();//Exception after second call
   //edit code////
   System.Runtime.InteropServices.Marshal.ReleaseComObject(mailItem);
   mailItem = null;
   ///////////////
   this.eventAggregator.GetEvent<ExportEmailEvent>().Publish(mailItem);
}

When I first time press button this code works fine. But second time I get exception:

System.Runtime.InteropServices.COMException{"The operation cannot be performed because the message has been changed."}

Exception is on mailItem.Save();.


Solution

  • First of all, I'd suggest releasing underlying COM objects ionstantly. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object. You can read more about that in the Systematically Releasing Objects article.

    Is the message class changed after your first call? Did you try to debug the code? Is there any difference? Is it a new message (not-saved yet)?