I have written some C# programs that read from Excel files and output Excel files. However, I have noticed that at the end of the day I have a LOT of Excel processes still running after the programs have terminated and all files have been closed. Here is how I am handling the file creation and closing:
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = (Worksheet)wb.Worksheets[1];
...
wb.Close(true, saveDirectory + "\\" + reportName, false);
xlApp.Quit();
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(xlApp);
this.Close();
Am I missing something? Any advice is appreciated.
Regards.
Your code is not releasing all COM references (e.g.
xlApp.Workbooks.Addcreates a reference to aWorkbooksobject that is never released). Therefore the Excel instance does not close, as described in this KB article, and discussed at length in numerous StackOverflow questions.The Excel instances will eventually shut down after your process has terminated, when COM detects that there hasn’t been a ping from the client for a while.