Why is this using () giving me an error?

I am trying to open (actually) an excel file. I am opening an application, but I want to use Using () functionality around each of the books that I open. Why does this lead to an error?

using (Excel.Workbook wbXL = appXL.Workbooks.Open(_sourceFullPath, Type.Missing, Excel.XlFileAccess.xlReadOnly)) { //stuff with wbXL } 

uses a red underline and says "Microsoft.Office.Interop.excel.Workbook": The type used in the using statement must be implicitly convertible to "System.IDisposable".

How to do it?

+8
c # excel interop using
source share
5 answers

To a large extent, he says that you can only use using with classes that implement IDisposable, so under the covers the compiler knows which function to call when finished - yourclass.Dispose() . Excel interaction classes do not implement this.

So, you have two options:

  • Create your own wrapper class for Excel.Workbook that implements IDispose and either the object itself calls method calls or wraps these methods, for example.

     public class DisposableWorkbook : IDisposable { private Excel.Workbook _workbook = null; public DisposableWorkbook(Excel.Application appXL, String path, NotSureOfType otherArgument, Excel.XlFileAccess access) { _workbook = appXL.Workbooks.Open(path, otherArgument, access); } public Excel.Workbook Workbook { get { return _workbook; } } public void Dispose() { if (workbook != null) { workbook.Close(Excel.XlSaveAction.xlDoNotSaveChanges, workbookToClose); workbook = null; } } } using (DisposableWorkbook dwbXL = new DisposableWorkbook(appXL, _sourceFullPath, Type.Missing, Excel.XlFileAccess.xlReadOnly)) { Excel.Workbook wbXL = dwbXL.Workbook; // stuff with wbXL } 
  • Contribute using yourself, for example.

     Excel.Workbook wbXL = null; try { wbxl = appXL.Workbooks.Open(_sourceFullPath, Type.Missing, Excel.XlFileAccess.xlReadOnly); //stuff with wbXL } finally { if (wbxl != null) wbxl.Close(); } 
+29
source share

Any element in a using statement must implement the IDisposable interface. I have no documentation, but I think Excel.Workbook does not implement this interface.

+2
source share

using Statement (link to C #) :

Provides convenient syntax to ensure proper use of IDisposable objects.

Excel.Workbook does not implement IDisposable , so you cannot use using for it.

+1
source share

You cannot make it work.

The using block is used to free resources from objects that implement the IDisposable interface as quickly and safely as possible.

Excel.Workbook does not implement IDisposable , so you cannot declare it for use in the using block.

+1
source share
 Businessmanger emb = new Businessmanger(); try { TempData["deparmentList"] = Deplist; return PartialView("create"); } catch (Exception) { throw; } finally { //object dispose here ((IDisposable)emb).Dispose(); } 
-one
source share

All Articles