1

Possible Duplicate:
How to properly clean up Excel interop objects in C#

I am having a set of functions. If that function passes, then I am printing some messages in an excel sheet called WebServices_output.xlsx through a function called ExcelRecorder() If it fails, then I am passing some failed messages through ExcelRecorder()

Am posting my code below

public void ExcelRecorder(int error, string detailmessage, string message, int row)
        {  
            Excel.Application xlApp = new Excel.Application();                
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/WebServiceTestCases_Output.xlsx");
            Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;           
                if (!string.IsNullOrEmpty(message))
                {
                    ((Range)xlWorksheet.Cells[row, "M"]).Value2 = "FAIL";
                    ((Range)xlWorksheet.Cells[row, "N"]).Value2 = error;
                    ((Range)xlWorksheet.Cells[row, "O"]).Value2 = detailmessage;
                    ((Range)xlWorksheet.Cells[row, "P"]).Value2 = message;
                }
                else
                {
                    ((Range)xlWorksheet.Cells[row, "M"]).Value2 = "PASS";
                    ((Range)xlWorksheet.Cells[row, "N"]).Value2 = "";
                    ((Range)xlWorksheet.Cells[row, "O"]).Value2 = "";
                    ((Range)xlWorksheet.Cells[row, "P"]).Value2 = "";
                }
            xlWorkbook.Save();
            xlWorkbook.Close(0,0,0);
            xlApp.Quit();
        }

Though I am particularly saving my workbook, closing it and then quitting it, when I open task manager, I see Excel.EXE still running. When I run ExcelRecorder() for five or six times, I see five or six Excel.EXE in my task manager and my program crashes.

What is wrong here? Why is the workbook not getting closed though I have added lines of code for closing it?

Community
  • 1
  • 1
user1501034
  • 343
  • 3
  • 6
  • 16

1 Answers1

2

You need to do this:

xlApp.Quit();

And then this:

System.Runtime.Marshal.ReleaseComObject(xlApp);
JMK
  • 27,273
  • 52
  • 163
  • 280