1

How to release excel instances created for my below code? Kill excel instances.

Excel.Workbook Workbook1 = xCel.Workbooks.Open(ExcelFilePath);                
Excel.Workbook Workbook2 = xCel.Workbooks.Add();

foreach (Excel.Worksheet dummysheet in Workbook1.Worksheets)
{                 
  dummysheet.Copy(Workbook2.Worksheets[1],Type.Missing);
}
Workbook2.SaveAs(strFileCopyPath);

//Code to release excel instances

if (sourceWorkbook != null)
                {                   
                    sourceWorkbook = null;
                    destinationWorkbook = null;
                    Thread.Sleep(500);
                }
                if (status.ProcessID > 0)
                 {                    
                    Process p = Process.GetProcessById(status.ProcessID);
                    p.Kill();
                 }

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

                try { Marshal.FinalReleaseComObject(sourceWorkbook); }
                catch { }
                try { Marshal.FinalReleaseComObject(destinationWorkbook); }
                catch { } 

Please check if this is correct.

I know this is duplicate, all i`m askng you people is to check if this is correct.

user2144293
  • 213
  • 4
  • 10
  • 17
  • Maybe look at the answer here - http://stackoverflow.com/q/9581689/2065121 – Roger Rowland Apr 25 '13 at 07:09
  • Don't use more than one dot per line when using the interop objects. So something like this: `ES.oXL.Workbooks.Open(ExcelFilePath)` needs to be split into 4 lines unfortunately. This is explained in the link in @TimSchmelter's comment – Dan Apr 25 '13 at 07:13

1 Answers1

0

Can use following:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Freelancer
  • 9,008
  • 7
  • 42
  • 81