Have a small problem. Im opening an excel spreadsheet via Interop wrappers. I need to intercept when the document closes again and prompt the user. My problem is that excel never closes, somehow i keep having references to something. I tried all the tutorials i could find, read all the blogposts here on stack, but i must be missing something. Below is my code (please note that everything is commented out, and now i kill all processes - this is not desired behavior):
private Action currentCallback;
Microsoft.Office.Interop.Excel.Application appExcel;
public bool OpenDocumentWithCallback(string path, Action callbackMethod)
{
bool result = true;
try
{
currentCallback = callbackMethod;
appExcel = new Application();
appExcel.Visible = true;
Workbooks books = appExcel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook docExcel = books.Open(Filename: path, ReadOnly: false);
appExcel.WorkbookBeforeClose += appExcel_WorkbookBeforeClose; // <-- hooking the event
}
catch (Exception ex)
{
result = false;
LogEntry.GetLogInterface().WriteDebugExceptionEntry(ex.ToString(), ex, SystemData.LogLevel.Critical);
}
return result;
}
void appExcel_WorkbookBeforeClose(Workbook Wb, ref bool Cancel)
{
GC.Collect();
GC.WaitForPendingFinalizers();
Wb.Close();
//Marshal.FinalReleaseComObject(Wb);
//appExcel.Visible = false;
//KillExcel(GetExcelProcess());
MurderAllExcelProcesses(); <--- last resort - killing all processes
//appExcel.Quit();
//Marshal.FinalReleaseComObject(appExcel);
currentCallback(); //<-- after this delegate is called i cannot access the excel file because it is in use by another application ???
}
Any help in figuring this out is highly appreciated