2017-05-04 36 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