I am trying to open an (hundreds actually) excel file(s). I open the application but want to use the Using() functionality around each of the workbooks I open. Why is this resulting in an error?
using (Excel.Workbook wbXL = appXL.Workbooks.Open(_sourceFullPath, Type.Missing, Excel.XlFileAccess.xlReadOnly))
{
//stuff with wbXL
}
using gets the red underline and says "'Microsoft.Office.Interop.excel.Workbook':Type used in a using statement must be implicitly convertible to 'System.IDisposable'.
How to make this work?
Pretty much what it says - you can only use
using
with classes that implement IDisposable, so that under the covers the compiler knows which function to call on finalisation -yourclass.Dispose()
. The Excel interop classes don't implement this.So you've got two choices:
Write your own wrapper class for Excel.Workbook that implements IDispose and either exposes the object itself to call methods on, or wraps those methods too, e.g.
Implement
using
yourself, e.g.You can't make it work.
The
using
block is used to free resources from objects that implement theIDisposable
interface as quickly and as safely as possible.Excel.Workbook
does not implementIDisposable
so you can't declare it for use in ausing
block.using Statement (C# Reference):
Excel.Workbook
does not implementIDisposable
, so you can't useusing
for it..Any item in a
using
statement must implement theIDisposable
interface. I haven't got the documentation to hand, but I'll guessExcel.Workbook
doesn't implement this interface.