Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 5th, 2012  |  syntax: None  |  size: 1.42 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Excel process remains open after interop; traditional method not working
  2. private void TestExcel()
  3.     {
  4.         Excel.Application excel = new Excel.Application();
  5.         Excel.Workbooks books = excel.Workbooks;
  6.         Excel.Workbook book = books.Open("C:\test.xlsm");
  7.  
  8.         book.Close();
  9.         books.Close();
  10.         excel.Quit();
  11.  
  12.         Marshal.ReleaseComObject(book);
  13.         Marshal.ReleaseComObject(books);
  14.         Marshal.ReleaseComObject(excel);
  15.     }
  16.        
  17. xlApp.Quit();
  18.  
  19.         //release all memory - stop EXCEL.exe from hanging around.
  20.         if (xlWorkBook != null) { Marshal.ReleaseComObject(xlWorkBook); } //release each workbook like this
  21.         if (xlWorkSheet != null) { Marshal.ReleaseComObject(xlWorkSheet); } //release each worksheet like this
  22.         if (xlApp != null) { Marshal.ReleaseComObject(xlApp); } //release the Excel application
  23.         xlWorkBook = null; //set each memory reference to null.
  24.         xlWorkSheet = null;
  25.         xlApp = null;
  26.         GC.Collect();
  27.        
  28. public static class ComBlackBox
  29. {
  30.     public static void ReleaseObject(object obj)
  31.     {
  32.         try
  33.         {
  34.             System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
  35.             obj = null;
  36.         }
  37.         catch (ArgumentException ex)
  38.         {
  39.             obj = null;
  40.             MessageBox.Show("Unable to release the Object " + ex.Message);
  41.         }
  42.         finally
  43.         {
  44.             GC.Collect();
  45.         }
  46.     }
  47. }