C# 如何在c中自动关闭outlook#

C# 如何在c中自动关闭outlook#,c#,outlook,C#,Outlook,我正在创建一个程序,将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

我正在创建一个程序,将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);
Microsoft.Office.Interop.Outlook.Application app=new Microsoft.Office.Interop.Outlook.Application();
字符串文件名=System.IO.Path.GetFileNameWithoutExtension(msgLocation)+“.html”;
字符串attachmentFiles=System.IO.Path.Combine(System.IO.Path.GetTempPath(),System.IO.Path.GetFileNameWithoutExtension(msgLocation)+“\U文件”);
string extractLocation=System.IO.Path.Combine(System.IO.Path.GetTempPath(),文件名);
Console.WriteLine(文件名);
Console.WriteLine(附件文件);
控制台写入线(提取位置);
var item=app.Session.OpenSharedItem(msgLocation)作为Microsoft.Office.Interop.Outlook.MailItem;
SaveAs(extractLocation,Microsoft.Office.Interop.Outlook.OlSaveAsType.olHTML);
int att=item.Attachments.Count;
如果(附件>0)
{

对于(int i=1;i,问题在于outlook com对象保留引用并阻止应用关闭。使用以下函数并将“应用”对象传递给它:

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

请参见

我尝试过,先生,但过程仍然存在。在我上面的代码中,我有类似的代码系统。Runtime.InteropServices.Marshal.ReleaseComObject(app);您是否在调用.Quit()之前调用Release?你需要在finally块中将其设置为null。并且也为你的Item对象设置+2以参考这些最佳实践你最后做了什么?