OpenSharedItem for opening .MSG files showing Error in Outlook C#

一世执手 提交于 2019-12-06 07:20:21

Would any combination of the Quit[1], Close[2] or ReleaseComObject[3] methods work for you? My code worked better but not perfect after I used them.[4]

using Outlook = Microsoft.Office.Interop.Outlook;

.
.
.

var app = new Outlook.Application();
var item = app.Session.OpenSharedItem(msgfile) as Outlook.MailItem;

//Do stuff with the mail.

item.Close(OlInspectorClose.olDiscard);
app.Quit();
Marshal.ReleaseComObject(item);

Another solution, according to Microsoft - Help and Support[5], is to delay the opening of the file. However, it doesn't sound like a good solution to me since, like @SliverNinja also said, you'll never know when Outlook releases its lock of the file.

Notes and references

  1. http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._application.quit.aspx, read 2014-10-14, 16:19.
  2. http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._mailitem.close%28v=office.15%29.aspx, read 2014-10-14, 16:19.
  3. http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject.aspx, read 2014-10-14, 16:19.
  4. For example, if I had opened Outlook for som regular work, the Quit-method would close that window as well.
  5. http://support2.microsoft.com/kb/2633737, read 2014-10-08, 16:19.

Outlook manages its own cache of items when you are opening and closing messages. Your best bet would be to use a randomly generated filename (i.e. Path.GetRandomFilename) when opening via OpenSharedItem so that you don't get issues. I would also use a temporary path instead of root c:\ (i.e. Path.GetTempPath).

You can try and free the MailItem reference (i.e. setting it to null), but there is no guarantee when Outlook will release the item from its cache.

You can use Redemption for that - call RDOSession.GetMessageFromMsgFile.
If you need to release the message immediately after you are done, use Marshal.ReleaseComObject()
In case of Redemption, you can also cast RDOMail object to the IDisposable interface and call IDisposable.Dispose().

ghostwriter

Hello you have two options .

  • set the Read-only attribute to the msg file

or

  • disable the following permissions for the users or usergroups to the parent folder:

    • Write Attributes
    • Write Extended Attributes

the msg file can now open multiple times but is write protect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!