2

When I run following code it still doesn't releasing excel object.

enter image description here

 public static List<string> GetExcelSheets(string FilePath)
        {
            Microsoft.Office.Interop.Excel.Application ExcelObj = null;
            Workbook theWorkbook = null;
            Sheets sheets = null;

            try
            {
                ExcelObj = new Microsoft.Office.Interop.Excel.Application();
                if (ExcelObj == null)
                {
                    MessageBox.Show("ERROR: EXCEL couldn't be started!");
                    System.Windows.Forms.Application.Exit();
                }

                theWorkbook = ExcelObj.Workbooks.Open(FilePath, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
                List<string> excelSheets = new List<string>();

                sheets = theWorkbook.Worksheets;
                foreach (Worksheet item in sheets)
                {
                    excelSheets.Add(item.Name);
                }

                return excelSheets;
            }
            catch (Exception ex)
            {
                return new List<string>();
            }
            finally
            {
                // Clean up.
                releaseObject(sheets);
                releaseObject(theWorkbook);
                releaseObject(ExcelObj);
            }
        }

        private static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
John Saunders
  • 160,644
  • 26
  • 247
  • 397
SOF User
  • 7,590
  • 22
  • 75
  • 121
  • 1
    related: http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c-sharp – JMax Jan 04 '12 at 14:21

2 Answers2

0

You forgot to keep a reference to ExcelObj.Workbooks and to release it:

Workbooks workbooks;
...
workbooks = ExcelObj.Workbooks;
theWorkbook = workbooks.Open(...
...
releaseObject(sheets);
releaseObject(theWorkbook);
releaseObject(workbooks);
releaseObject(ExcelObj);
phoog
  • 42,068
  • 6
  • 79
  • 117
-1

Try this code:

ExcelObj.Quit();
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
William
  • 551
  • 2
  • 10
  • 24
  • In future, rather than adding meaningless numbers to pad out the minimum length, I suggest adding an explanation, however brief. This might also ward off those pesky VLQ flags. – Nathan Tuggy May 08 '15 at 00:42