gpt4 book ai didi

c# - 如何在 C# 中自动化后关闭 Outlook

转载 作者:行者123 更新时间:2023-11-30 23:13:03 25 4
gpt4 key购买 nike

我正在创建一个将 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() 没有关闭应用。

最佳答案

问题是 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/

关于c# - 如何在 C# 中自动化后关闭 Outlook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43772401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com