【问题标题】:How to close outlook after automating it in c#如何在 C# 中自动关闭 Outlook
【发布时间】:2021-01-22 11:58:22
【问题描述】:

我正在创建一个将 Msg Outlook 文件转换为 pdf 的程序。我所做的是将 Msg 文件导出为 Html,然后将 Html 输出转换为 pdf。这是我的代码:

Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();

string filename = System.IO.Path.GetFileNameWithoutExtension(msgLocation) + ".html";
string attachmentFiles = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetFileNameWithoutExtension(msgLocation) + "_files");
string extractLocation = System.IO.Path.Combine(System.IO.Path.GetTempPath(), filename);

Console.WriteLine(filename);
Console.WriteLine(attachmentFiles);
Console.WriteLine(extractLocation);
var item = app.Session.OpenSharedItem(msgLocation) as Microsoft.Office.Interop.Outlook.MailItem;
item.SaveAs(extractLocation, Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML);

int att = item.Attachments.Count;
if (att > 0)
{
    for (int i = 1; i <= att; i++)
    {
        item.Attachments[i].SaveAsFile(System.IO.Path.Combine(attachmentFiles, item.Attachments[i].FileName));
    }
}

app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

MSG 文件转换为 HTML 工作正常,但为什么 outlook.exe 仍在运行?我想关闭它,但app.Quit() 没有关闭应用程序。

【问题讨论】:

  • 你最后做了什么?

标签: c# outlook


【解决方案1】:

问题在于 Outlook com 对象保留引用并阻止应用程序关闭。使用以下函数并将您的“app”对象传递给它:

private void ReleaseObj(object obj)
{
    try 
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
    }
    finally 
    {
        obj = null;
    }
}

https://blogs.msdn.microsoft.com/deva/2010/01/07/best-practices-how-to-quit-outlook-application-after-automation-from-visual-studio-net-client/

【讨论】:

  • 我试过了,先生,但过程仍然存在。在我上面的代码中,我有类似的代码 System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
  • 你是在调用 .Quit() 之前调用 Release 吗?
  • 你需要在finally块中设置为null。
  • 对你的 Item 对象也这样做
  • +2 参考这些最佳实践
猜你喜欢
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
相关资源
最近更新 更多