C#Outlook 2007 COM互操作应用程序不退出!

前端之家收集整理的这篇文章主要介绍了C#Outlook 2007 COM互操作应用程序不退出!前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
任何想法为什么以下代码退出通过COM互操作创建的Outlook 2007进程?
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();

var item = app.Session.OpenSharedItem("C:\\test.msg") as Microsoft.Office.Interop.Outlook.MailItem;
string body = item.HTMLBody;
int att = item.Attachments.Count;

(item as Microsoft.Office.Interop.Outlook._MailItem).Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olDiscard);
System.Runtime.InteropServices.Marshal.ReleaseComObject(item);

(app as Microsoft.Office.Interop.Outlook._Application).Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
System.Diagnostics.Debugger.Break();

一个几乎相同的使用Word的片段工作,所以我想知道我是否忘记清理一些东西……

解决方法

您的代码中引用了第三个COM对象:app.Session.这也必须正确发布.试试这段代码
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook.NameSpace session = null;
Microsoft.Office.Interop.Outlook.MailItem item = null;

try {
    app = new Microsoft.Office.Interop.Outlook.Application();
    session = app.Session;
    item = session.OpenSharedItem("C:\\test.msg") as Microsoft.Office.Interop.Outlook.MailItem;

    string body = item.HTMLBody;
    int att = item.Attachments.Count;

    (item as Microsoft.Office.Interop.Outlook._MailItem).Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olDiscard);

    (app as Microsoft.Office.Interop.Outlook._Application).Quit();
} finally {
    if(item != null) {
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(item);
    }
    if(session != null) {
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(session);
    }
    if(app != null) {
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
    }
}
原文链接:https://www.f2er.com/c/118919.html

猜你在找的C&C++相关文章