I have a c# application that creates a simple excel file. This work fine. I however want to make sure the excel application that is created is closed no matter what happens so I don't get lots of Excel processes running in the background.
Below is some code I'm using. I guess my question is in the Dispose method is there a way to test if the XlApp is still open and if so make sure the application is quitted.
Is it just as simple as the few lines below?
if (XlApp != null)
{
XlApp.Quit();
releaseObject(XlApp);
}
My code example
public class ExcelMain : IDisposable
{
public void MadeUpMethod()
{
// do some stuff here
XlApp.Quit(); // worried that if the line is not reached will the excel application be closed
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (Rng != null) releaseObject(Rng);
if (XlWorksheet != null) releaseObject(XlWorksheet);
if (XlSheets != null) releaseObject(XlSheets);
if (XlWorksheets != null) releaseObject(XlWorksheets);
if (XlWorkbook != null) releaseObject(XlWorkbook);
if (ActiveWindow != null) releaseObject(ActiveWindow);
if (XlApp != null) releaseObject(XlApp);
}
}
private static void releaseObject(object obj)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
}
}