1

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

2 Answers 2

1

Try to open the workbooks etc. with using() Block! This will close and give free all resources.

Sign up to request clarification or add additional context in comments.

Comments

0

You don't ever set appExcel = null (you might need to set the workbook reference to null too). You should do that before calling any garbage collection explicitly (which really ought not be necessary).

Try not to kill the excel process: Excel 2013, for example, normally runs many Excel sessions in one executable. You could make yourself unpopular if you close such sessions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.