DotNet only release the COM object after all the handles have been released. What I do is comment everything out, and then add back a portion. See if it release Excel. If it did not follow the following rules. When it release, add more code until it does not release again.
1) When you create your Excel variables, set all the values to null (this avoid not initiated errors)
2) Do not reuse variables without releasing it first Marshal.FinalReleaseComObject
3) Do not double dot (a.b = z)
. dotNet create a temporary variable, which will not get released.
c = a.b;
c = z;
Marshal.FinalReleaseComObject(c);
4) Release ALL excel variables. The quicker the better.
5) Set it back to NULL.
Set culture to "en-US". There is a bug that crash Excel with some cultures. This ensure it won't.
Here is an idea of how your code should be structured:
thisThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
InteropExcel.Application excelApp = null;
InteropExcel.Workbooks wkbks = null;
InteropExcel.Workbook wkbk = null;
try
{
excelApp = new InteropExcel.Application();
wkbks = excelApp.Workbooks;
wkbk = wkbks.Open(fileName);
...
}
catch (Exception ex)
{
}
if (wkbk != null)
{
excelApp.DisplayAlerts = false;
wkbk.Close(false);
Marshal.FinalReleaseComObject(wkbk);
wkbk = null;
}
if (wkbks != null)
{
wkbks.Close();
Marshal.FinalReleaseComObject(wkbks);
wkbks = null;
}
if (excelApp != null)
{
// Close Excel.
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
excelApp = null;
}
// Change culture back from en-us to the original culture.
thisThread.CurrentCulture = originalCulture;
}