Excel file remaining locked for editing after use

1.2k Views Asked by At

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
1

There are 1 best solutions below

0
TnTinMn On BEST ANSWER

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