I have a function basically to convert an excel file to text file. The structure is like following. What I am concerned is the Finally part? Is it a best practise to kill the excel?
Excel.Application excel=new Excel.Application();
Excel.Workbook wb=excel.Workbooks.Open(…);
Try
{
…
Foreach(Excel.Worksheet sheet in wb.Sheets)
{
…
Marshal.RealseComObject(sheet);
}
…
}
Catch()
{
}
Finally
{
wb.Close(false, missing, missing);
while (Marshal.ReleaseComObject(wb)!=0)
{
}
wb=null;
excel.Quit();
while (Marshal.ReleaseComObject(excel)!=0)
{
}
excel=null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
Update:
I have following version of Finally
Finally{
wb.close(false, missing, missing);
excel.application.quit();
excel.quit();
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(excel);
GC.Collect();
GC.WaitForPendingFinalizers();
}
Which one is better (make more sense)? I have checked all the links here, but there is no finally answer, everybody's answer is sightly difference. I am not sure which one is the best?