2

I have a Windows Forms application with an OpenFileDialog. The user clicks a "Process" button and the application goes through the file - an Excel spreadsheet - and processes the data in it. All of this works as expected with one caveat.

After the application is done processing, the file remains locked for editing so when I open the file to make changes, I get this message:

locked for editing

If I close the application completely, the file is unlocked so I'm assuming the application is just holding onto the file for longer than it should. I'm guessing there should be some sort of Close() method or something that will release the resources but I can't figure out exactly what I need. I tried using Dispose() and wrapping my code in a Using block which I thought destroyed everything automatically but no luck.

Here's my code:

Using excel = New ExcelPackage(OpenFileDialog1.OpenFile)
    Dim ws = excel.Workbook.Worksheets.First()

    'Process data in ws...

    OpenFileDialog1.Dispose() 'Doesn't seem to release the file
    excel.Dispose() 'Doesn't seem to release the file
End Using
TheIronCheek
  • 1,077
  • 2
  • 20
  • 50
  • Read the second part of the notes here: [Get running instances of Excel](https://stackoverflow.com/a/51791847/7444103) and see the links to other SO answers that show how other people have solved the same problem. – Jimi Mar 03 '20 at 15:50
  • Maybe consider a try/finally. You can put `Close()` code in the finally block. – tgolisch Mar 03 '20 at 16:44
  • @tgolisch - What `Close()` code do I use? Just the same `Dispose()` I'm already calling? – TheIronCheek Mar 03 '20 at 16:47
  • `OpenFileDialog1.OpenFile` returns an `Stream` object. Try wrapping your code with `Using strm As IO.Stream = OpenFileDialog1.OpenFile ... End Using` then pass `strm` to the `New ExcelPackage` constructor. – TnTinMn Mar 03 '20 at 17:00
  • @TnTinMn - Yahtzee! That did the trick. If you put that into an answer, I'll accept. – TheIronCheek Mar 03 '20 at 17:10

1 Answers1

2

The OpenFileDialog.OpenFile Method returns a Stream object that likely is not being closed by the ExcelPackage.

To ensure that the stream is released, use the following pattern.

Using strm As IO.Stream = OpenFileDialog1.OpenFile
  Using excel = New ExcelPackage(strm)
      ' ...
  End Using
End Using
TnTinMn
  • 11,522
  • 3
  • 18
  • 39