1

I`m trying to get copy of one worksheet to another worhsheet,below is my code..I tried to release instances created of excel but still I see one instace of it in TaskManager.

C# Code:

try
{
  wBook = xCel.Workbooks.Open(filePath);
  xCel.Visible = false;
  this.xCel.DisplayAlerts = false;                
  wBook = (Excel.Worksheet)wBook.Worksheets.get_Item(1);
  wBook.Copy(Type.Missing, Type.Missing);                
  wBook = (Excel.Worksheet)wBook.Sheets[1];                
  wBook.SaveAs(strFileCopyPath);                 
}
finally
{
  if (wBook != null)
  {   wBook.Close();                    
      Thread.Sleep(500);
  }                
  Marshal.ReleaseComObject(wBook);               
  Marshal.ReleaseComObject(wBook);                
}

Please some one tell what wrong i`m doing here? thanks

user2144293
  • 213
  • 4
  • 10
  • 17
  • See [here](http://stackoverflow.com/q/13572004/976080) for how and when to release objects, and [here](http://stackoverflow.com/q/13069153/976080) for limiting use of "two dots". When you call `wBook.Worksheets.get_Item(1);` an intermediate `Worksheets` object is created, but since you don't have a reference to it you can't release it. – Sid Holland Mar 12 '13 at 16:36

2 Answers2

0

You forgot to call Quit() method of Excel.Application object. Ususally I use the following code to close Excel (VB.Net code snippet):

xlApp.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
xlApp = Nothing
xlBook = Nothing
xlSheet = Nothing
Andrey Gordeev
  • 30,606
  • 13
  • 135
  • 162
0

You are doing nothing SANE wrong - but the concept of closing exel is very harebrained. Thats because: 1: Excel creates sometimes intermediate objects, which are NOT visible for you, especially if you do something like this: DIm bla = excel.worksheet.range("A1").value. Then there are intermediate objects for excel. 2: The excel objects have to be closed in a very specific order.

This code SHOULD help:

GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()

this has to be double due to the fact that pass 1 only marks intermediate objects, but does not destroy them. It is garbage collection.

Also destroy your objects in this order: Ranges etc. Worksheets Workbook APP

like this:

System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlSheet)
xlsheet = nothing
xlBook .Close()
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlBook )
xlbook = nothing
xlapp.quit
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlapp)
xlapp = nothing

use try catch to catch errors in this section, if an object is nothing..

Christian Sauer
  • 10,351
  • 10
  • 53
  • 85