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

标签 c# com interop outlook-2007 office-interop

知道为什么以下代码不退出通过 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);
    }
}

关于C# Outlook 2007 COM 互操作应用程序不退出!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1907270/

相关文章:

c# - 在 C# 中忽略异常

c# - 如何在 Visual Studio 2008 中自动发布网站?

.net - .NET 是否使原始 COM 和 DCOM 编程变得多余?

c# - 如何防止 Excel 互操作在插入图像时窃取焦点

c# - 将记录添加到数据库后在特定时间触发 WebJob

c++ - 如何向上查询或向下查询接口(interface)指针?

interface - COM 对象到 COM 接口(interface)的 dynamic_cast 不会影响引用计数,是吗?

C# 编码非托管指针返回类型

javascript - 无法将焦点设置在表格行上

c# - C# 中的引用类型如何分配内存?