10

We developed an application that uses Excel interop libraries (Microsoft.Office.Interop.Excel) to read some Excel files.

When a problem occur in the application, the event Application.ThreadException is handled, so the resources are released (Excel is closed...).

The problem is that when we use the VS debugger, if we stop the execution (because the process breaks on an exception, or a breakpoint, there are lots of reasons why we'd do that), the resources are not released and Excel stays opened. And of course, next time the application is launched... it crashes because there are locks on the file.

So I'm looking for a way to force the release of the Excel objects, even when stopped with the debugger.

Any suggestion ?

Julien N
  • 3,738
  • 4
  • 26
  • 43

3 Answers3

15

You can use the DTE (VisualStudio Automation Model) to write a macro that will be invoked when a stop debug happens, below is a snippet of the idea.

Private Sub DebuggerEvents_OnEnterBreakMode(
   ByVal Reason As EnvDTE.dbgEventReason, 
   ByRef ExecutionAction As EnvDTE.dbgExecutionAction) Handles DebuggerEvents.OnEnterBreakMode
    If (Reason = dbgEventReason.dbgEventReasonStopDebugging) Then
        // DO YOUR CLEAN UP CODE HERE
    End If
End Sub
Shay Erlichmen
  • 31,099
  • 7
  • 64
  • 86
1

Unfortunately there isn't a way to do this. The stop button in visual studio kills the process, so it doesn't have any chance to clean up.

As a possible way round your problem (although not a very good one), you could write a cleanup routine and execute it manually from the immediate window before stopping the app.

[Edit: Ignore me. This answer is wrong. Shay Erlichmen has come up with a much better solution using a macro]

Simon P Stevens
  • 26,147
  • 3
  • 73
  • 103
1

One possibility is to switch to a pure .NET solution such as SpreadsheetGear for .NET to get away from the performance and reliability problems associated with COM interop.

Disclaimer: I own SpreadsheetGear LLC

Joe Erickson
  • 6,836
  • 1
  • 29
  • 31
  • Would be nice but a little expensive as we just need to read an excel file :). I looked into open source solutions (like Koogra http://koogra.sourceforge.net/) but it doesn't work with our XLS files. – Julien N Jun 25 '09 at 13:04