I am using the Excel interop in C# in my web site project to parse an excel file and convert it to a text file. The sample code is as following.
Excel.Application excel=new Excel.Application();
Excel.Workbooks wbs=excel.Workbooks;
Excel.Workbook wb=wbs.Open(…);
Try
{
…
Foreach(Excel.Worksheet sheet in wb.Sheets)
{
…
Marshal.RealseComObject(sheet);
sheet=null; //compiler error
}
…
}
Catch()
{
}
Finally
{
wb.Close(false, missing, missing);
while (Marshal.ReleaseComObject(wb)!=0)
{
}
wb=null;
while (Marshal.ReleaseComObject(wbs)!=0)
{
}
wbs=null;
excel.Quit();
while (Marshal.ReleaseComObject(excel)!=0)
{
}
excel=null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
My question is do I need to release the worksheet object in the foreach loop? I saw a few sample codes about programming with excel worksheet, none of them do. If I do need to relase the object, in my foreach loop, i couldn't set the sheet to null, does it mean i shouldn't use foreach?