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. It worked well in the debug mode. But in Task Manager I often see two Excel are running, why?. In addition after deployed the web site to IIS, the excel.exe will not quit. My project is a web site project in VS 2010 (Ultimate). My machine is Windows Server 2008, which means I should have IIS 7. But when I run the inetmgr, it shows IIS version 6 (after googling, I confirmed that my IIS should be still 7, the management tool is 6).
So my question is why Excel is not quitting after I deployed to IIS?
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);
}
…
}
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();
}
Updated: it turned out it was because wbs.Open(…)
threw an exception.
I found the solution from following link and it fixed my problem. Cannot open Excel file in C#