0

I am rather new here. I have search this forum and I saw that double dot a COM object is not good, I have changed the open() to one dot. But I am still unable to kill off the processes. Added the Marshal.ReleaseComObject and it still didn't work. Anybody can point out the error in my code? Thanks.

               Application excel = new Application();
                try
                {
                    //excel.Workbooks.Open(filePath); //Apparently double dot for COM object is not a good practice
                    var excelworkbooks = excel.Workbooks;
                    var openworkbook = excelworkbooks.Open(filePath);

                    excel.Visible = false;
                    if (excel.Workbooks.Count > 0)
                    {
                        IEnumerator wsEnumerator = excel.ActiveWorkbook.Worksheets.GetEnumerator();
                        object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;

                        while (wsEnumerator.MoveNext())
                        {
                            Microsoft.Office.Interop.Excel.Worksheet wsCurrent = (Microsoft.Office.Interop.Excel.Worksheet)wsEnumerator.Current;
                            String outputFile = "OutputFile.html";
                            if(!File.Exists(filePath+outputFile))
                            {
                                wsCurrent.SaveAs(filePath + outputFile, format);
                            }
                            break;
                        }
                    }
                    excel.Workbooks.Close();
                    excel.Application.Quit();
                    excel.Quit();

                    Marshal.ReleaseComObject(excelworkbooks);
                    Marshal.ReleaseComObject(openworkbook);
                }
                finally
                {                        
                    Marshal.ReleaseComObject(excel.Workbooks);
                    Marshal.ReleaseComObject(excel.Application);
                    Marshal.ReleaseComObject(excel);
                }
Chua
  • 1
  • You will get a tonne of various answers to this, Some will work, and some wont. This is because if you use this method of approach and get it working, you can change the code later and use a different part of the object model an unknowingly have a reference to some object. For the real world, where code is complicated, you can spend days tracking this down. My suggestions are 1. Use an application domain. The references are sorted on your behalf during process tear down. 2. Use VSTO. This internally uses an application domain and will do the same. – PaulG Jan 11 '16 at 08:45
  • Thanks @PaulG for this answer. I guess you are right. I will see what I can start learning from using an application domain and VSTO. :) – Chua Jan 12 '16 at 07:08

0 Answers0