How to stop the excel process created in my code

D

DAXU

Hello,
I did following code to open an excel sheet and now just close it. But
the problem is that the excel process created in my code is still
there when I use:
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
What else should I do to properly shutdown the excel process?

many Thanks.

Here is my code:
Microsoft.Office.Interop.Excel.Application excelApp=null;
Microsoft.Office.Interop.Excel.Workbook newWorkbook =
null;
Microsoft.Office.Interop.Excel.Sheets excelSheets = null;
Microsoft.Office.Interop.Excel.Worksheet sheet = null;
try
{
excelApp = new
Microsoft.Office.Interop.Excel.ApplicationClass();
//openExcelDoc.InitialDirectory =
string.Format(@"{0}Carweb", drives[0]);

excelApp.Visible = false;
newWorkbook =
excelApp.Workbooks.Open(templateExcelPath, 0, false, 5, "", "", false,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false,
0, true, false, false);
excelSheets = newWorkbook.Worksheets;
foreach (Microsoft.Office.Interop.Excel.Worksheet
excelWorksheet in excelSheets)
{
string name = excelWorksheet.CodeName;
name = excelWorksheet.Name;
}
}
finally
{
if (sheet != null)
{

Marshal.ReleaseComObject(sheet);
}
if (excelSheets != null)
{
Marshal.ReleaseComObject(excelSheets);
}
if (newWorkbook != null)
{
newWorkbook.Close(Missing.Value, Missing.Value,
Missing.Value);
Marshal.ReleaseComObject(newWorkbook);
}
if (excelApp != null)
{
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
}
 
N

Nicholas Paldino [.NET/C# MVP]

DAXU,

Well, you are leaking references which keep the Application instance
alive. Quit doesn't kill the process until the reference count on the
Application instance is 0.

Because you can get to the Application object from almost any object in
Excel, every object that you expose that you don't release, you add another
reference to the Application.

From what it looks like, you are calling the Workbooks property and not
releasing the reference that you expose as a result of calling the property.

You might want to look at this thread:

http://groups.google.com/group/micr...icholas+paldino+ComReference#1d7fb35d82ce3627

In it, there is a structure I provide which will help clean up code that
properly releases COM references in a method scope. The problem with your
code is that if an exception happens in the finally clause, you could end up
not releasing the other objects, and the app will continue to hang around.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top