I am using c# to create excel file. When my program is running the excel instance is created and showing in task manager. That is normal, but when my program closes, then the excel instance should not be shown in task manager, but it's showing. Please review my code and tell me what is my mistake there which causes the excel instance to be in task manager even after closing my apps. Here is my code.
private void GenerateExcel()
Excel.Application xlApp = new Excel.Application();
if (xlApp == null)
{
return;
}
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkBook.Windows.Application.ActiveWindow.DisplayGridlines = false;
xlWorkSheet.Cells[2, 2] = "Sheet 1 content";
if (!Directory.Exists(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Reports"))
{
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Reports");
}
string strpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Reports\\test.xls";
if (File.Exists(strpath))
{
File.Delete(strpath);
}
xlWorkBook.SaveAs(strpath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private 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();
}
}