I'm working on a C# project that uses Microsoft.Office.Interop.Excel.Application
to read values from an Excel file:
try {
Application xlApp = new Application();
Workbook workbook = xlApp.Workbooks.Open(filename)
// ... Load Excel values ...
} finally {
// ... Tidy up ...
}
In the finally
block I'd like to make sure everything is closed and disposed of properly so nothing hangs around in memory and Excel closes cleanly. Have seen various threads about what this code should look like (more complex than I thought!) but one thing it might include is:
if (workbook != null) {
workbook.Close();
// ... possibly also Marshal.FinalReleaseComObject(workbook);
}
However, this throws an error if the workbook is already closed so how can I safely check this? Would prefer not to just catch the error if possible as this type of thing tends to distort debugging. Is there a clean way of finding out the workbook state before closing?
One more q - am wondering if workbook.Close()
is needed if xlApp.Quit();
is done afterwards - would quitting the Excel application cause workbook.Close()
(and any COM object releasing) to happen implicitly?