I'm reading/writing an excel file using Interop library like so
(Update: this isn't a duplicate of Why does Microsoft.Office.Interop.Excel.Application.Quit() leave the background process running?, this question is about how to release excel from memory when there is an exception)
var myExcelApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbooks AllWorkbooks= xlApp.Workbooks;
Excel.Workbook MyWorkBook= //Open workbook
Excel.Worksheet MySheet= //Open worksheet
//Do the work
MyWorkBook.Close(false, file);
myExcelApp.Quit();
Marshal.FinalReleaseComObject(myExcelApp );
//FInalReleaseComObject for MyWorkBooks
This works OK except when an exception is thrown, and then Excel lingers on in the background and has to be killed off using the task manager.
I'm not sure what the best way is to release these COM objects. Should I use the using
blocks, or should I enclose everything in try catch like this?
Excel.Workbooks AllWorkbooks= null;
Excel.Workbook MyWorkBook=null;
Excel.Worksheet MyWorkshet=null;
Excel.Application myExcelApp=null;
try{
//Read file here
}
catch{
MyWorkBook?.Close(false, file);
myExcelApp?.Quit();
Marshal.FinalReleaseComObject(myExcelApp );
//FInalReleaseComObject for MyWorkBooks
}
Is the above the correct approach? I have to initialize excel objects as null, because they cannot be newed up.
Thanks