Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing EXCEL.exe Process from C# in a Windows Service

I have a windows service that opens up an Excel spreadsheet via the Microsoft.Office.Interop.Excel.Application object.

Application xlApp = new Application();
Workbook workbook = xlApp.Workbooks.Open(fileName, 2, false);
...
...
workbook.Close();
xlApp.Quit();

I would like to kill the EXCEL.exe process that is left running after it is done working with the workbook.

I've tried the following with no success...

// This returns a processId of 0
IntPtr processId;
GetWindowThreadProcessId(new IntPtr(xlApp.Hwnd), out processId);
Process p = Process.GetProcessById(processId.ToInt32());   
p.Kill();

Anyone have any ideas as to how I can do this via a Windows Service?

like image 505
thiag0 Avatar asked Apr 11 '11 21:04

thiag0


1 Answers

Properly closing the open Excel workbook and quitting the app is extremely difficult. If I can find the links I'll post them, but essentially you must clean up all references to any COM object that you create. This includes everything from ODBCConnections (data connections), Worksheets, Workbooks, and the Excel application. A combination I got to work involved garbage collection and the System.Runtime.InteropServices.Marshal object:

// Garbage collecting
GC.Collect();
GC.WaitForPendingFinalizers();
// Clean up references to all COM objects
// As per above, you're just using a Workbook and Excel Application instance, so release them:
workbook.Close(false, Missing.Value, Missing.Value);
xlApp.Quit();
Marshal.FinalReleaseComObject(workbook);
Marshal.FinalReleaseComObject(xlApp);

Like you mentioned, looping through and killing each Excel process is usually not a good idea, since if you're running this as a Windows app you may close Excel on your user, or in a service also close an instance of Excel that is running via some other program.

Edit: See this question for more info.

like image 189
dotNetkow Avatar answered Sep 21 '22 09:09

dotNetkow