I am doing a Windows Service, and I am using Microsoft.Office.Interop.Excel to create a new excel file, edit it, and save it.
After being done with it, and closing the appropriate objects (worksheet, workbook), quitting the excel app, and Marshal releasing COM objects, the process is still lingering.
private void doWork()
{
var excelApp = new MsExcel.Application();
var workBooks = excelApp.Workbooks;
var workbook = excelApp.Workbooks.Add();
var sheets = workbook.Sheets;
_worksheet = workbook.Sheets[1];
//Do Work Here
_worksheet.SaveAs(filePath);
workbook.Close(false,System.Reflection.Missing.Value,System.Reflection.Missing.Value);
workBooks.Close();
releaseObject(_worksheet);
releaseObject(sheets);
releaseObject(workbook);
releaseObject(workBooks);
excelApp.Quit();
releaseObject(excelApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
_log.Error($"Unable to release object {obj} Error:" + ex.ToString());
obj = null;
}
finally
{
GC.Collect();
}
}
I saw a couple of other posts that suggested the releasing of the objects, plus the reference to Workbooks and Sheets. Not sure, why this is still not working.