How do I programmatically kill a MS Excel process within my C# asp.net application that created and started the process

fbroccoli
fbroccoli used Ask the Experts™
on
I've written a C# asp.net application that uses Microsoft.Office.Interop.Excel.  Application creates an Excel spreadsheet, saves it and then tries to close and quite Excel but the Excel process is still running in the Task Manager.  (same code works in a console app or Windows Forms application but not in my asp.net web app).

Here is the basis of the code:

using MyExcel = Microsoft.Office.Interop.Excel;
.
.
.
MyExcel.Application xlApp;
MyExcel.Workbook xlWorkBook;
MyExcel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
.
.
 xlApp = new MyExcel.Application();
 xlWorkBook = xlApp.Workbooks.Add(misValue);
 xlApp.DisplayAlerts = false;
 xlWorkSheet = (MyExcel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
 xlWorkSheet.Name = "Daily Report";
.
.
xlWorkBook.SaveAs(myFile, MyExcel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, MyExcel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close();
xlApp.Quit();

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Nicolas LecanuAnalyst developer

Commented:
Hi fbroccoli,

You need to use the function "Application.Quit" method(Excel)

Here a exemple of this function.

Author

Commented:
My code contains:  xlApp.Quit();

Is my syntax incorrect?
Nicolas LecanuAnalyst developer

Commented:
You are right, sorry.

Can you try this function ?

    private void KillExcel()
    {
        Process[] AllProcesses = Process.GetProcessesByName("excel");

        // check to kill the right process
        foreach ( Process ExcelProcess in AllProcesses) {
        if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
         ExcelProcess.Kill(); 
        }

        AllProcesses = null;
    }

Open in new window

Ryan ChongSoftware Team Lead

Commented:
you can read this question which provide several options to do that:

C# Visual Studio question regarding how to kill Excel interop process.
https://www.experts-exchange.com/questions/29077256/C-Visual-Studio-question-regarding-how-to-kill-Excel-interop-process.html

Author

Commented:
Good morning Nicolas,

I have copied and pasted the function into my code.  What do I replace "MyHashtable" with so I can rebuild my application and test it?

Thank you,
Frank

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial