2

I use this code to convert an excel file to PDF. The problem is that the Excel process is not close. What am I missing?

        protected void Indexchanged_ConvertPDF(Object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

        xlApp.DisplayAlerts = false;
        xlApp.Visible = false;
        xlApp.ScreenUpdating = false;

        string path = CertificadosPresion.SelectedRow.Cells[0].Text;
        string CertName = CertificadosPresion.SelectedDataKey.Value.ToString();

        Workbook xlWorkbook = xlApp.Workbooks.Open(path);

        xlWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, @"C:\pdf\" + SALESID.Text + "_CertPres.pdf", 0, false, true);

        xlWorkbook.Close();
        xlApp.Quit();
        xlApp = null;
        xlWorkbook = null;

        DisposeCOMObject(xlWorkbook);
        DisposeCOMObject(xlApp);
    }
Barnabeck
  • 459
  • 1
  • 6
  • 26
  • xlApp = null and DisposeCOMObject(xlApp) after that looks quite strange. – Alex Butenko Dec 20 '15 at 23:37
  • try using the follow `Marshal.ReleaseComObject(xlWorkbook);` do the same for all the Interop Objects – MethodMan Dec 20 '15 at 23:43
  • Try to set DisplayAlerts, Visible and ScreenUpdating true before quitting, maybe you will see the reason, why it cannot close. – Alex Butenko Dec 20 '15 at 23:45
  • none of the suggested hints worked for me. Probably because I use the code in a web application driven automation which is not recommended as I've been reading. Nevertheless using the Garbage Collector the process gets closed successfully. GC.Collect(); GC.WaitForPendingFinalizers(); – Barnabeck Dec 22 '15 at 16:41

1 Answers1

0

It is not that easy as one might think. There is a nice article losing some words about this topic:

http://devcity.net/PrintArticle.aspx?ArticleID=239

But other than that I think that this question might be a duplicate of Closing Excel Application Process in C# after Data Access. There are a lot of potential solutions for your problem.

Community
  • 1
  • 1
idunno
  • 71
  • 8
  • GC.Collect(); GC.WaitForPendingFinalizers(); ... did the job! This was mentioned in the link you posted, but it took me much too long to step on it, as I was trying out various ways. – Barnabeck Dec 22 '15 at 16:36