2017-05-04 108 views
1

我正在创建一个将msg outlook文件转换为pdf的程序。我所做的是将Msg文件导出到Html中,然后将Html输出转换为pdf。这是我的代码:如何在c中自动完成后关闭outlook#

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()不能关闭应用程序。

回答

1

问题是outlook com对象持有引用并停止应用程序关闭。使用下面的功能,并通过您的“应用程序”对象是:

private void ReleaseObj(object obj) 
{ 
    try 
    { 
     System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); 
    } 
    catch {} 
    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/

+0

我尝试了爵士,但这个过程仍然存在。并在我的代码上面我有类似的代码System.Runtime.InteropServices.Marshal.ReleaseComObject(app);您打电话给.Quit()之前,您是否拨打了Release? –

+0

? – Rocklan

+0

,并且您需要在finally块中将其设置为null。 – Rocklan

相关问题