2017-05-04 5 views
1

Ich erstelle ein Programm, das Msg Outlook-Datei in PDF konvertiert. Was ich getan habe, war die Msg-Datei in HTML zu exportieren und dann die HTML-Ausgabe in PDF zu konvertieren. Dies ist mein Code:So schließen Sie Outlook nach der Automatisierung in C#

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); 

Die convertion MSG-Datei in HTML ist perfekt funktioniert, aber warum ist outlook.exe noch läuft? Ich möchte es schließen, aber app.Quit() schließt die App nicht.

Antwort

1

Das Problem ist, dass das Outlook-com-Objekt an Referenzen festhält und das Schließen der App stoppt. Verwenden Sie die folgende Funktion und übergeben Sie Ihre „app“ Objekt, um es:

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

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

+0

Ich versuchte es Sir, aber der Prozess ist immer noch da. und in meinem Code oben habe ich den ähnlichen Code System.Runtime.InteropServices.Marshal.ReleaseComObject (APP); –

+0

rufen Sie Release, bevor Sie .Quit() aufrufen? – Rocklan

+0

und Sie müssen es im finally-Block auf null setzen. – Rocklan

Verwandte Themen