Reputation: 1057
Actually I'm writing a small application (WinForms + C#), where I'm reading the Excel file. After exiting from the application and went to the task manager I found that Excel.exe is still running. And as I run my application several times I found multiple instances of Excel.exe running in the task manager.
So can somebody tell me as what needs to be done to kill "Excel.exe" each time I exit from the application...
The code is somewhat like this:
ApplicationClass appClass = new ApplicationClass();
Workbook workBook = appClass.Workbooks.Open(path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet workSheet = (Worksheet) workBook.ActiveSheet;
All under this namespace: Microsoft.Office.Interop.Excel; that is COM
Upvotes: 4
Views: 8237
Reputation: 736
In my case, in some task the excel instance still running after I did a app.Quit() call.
My solution was:
application = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Put app instance as null and do a forced call to GC.
Hope this help
Upvotes: 0
Reputation: 4284
Process[] pro = Process.GetProcessesByName("excel");
pro[0].Kill();
pro[0].WaitForExit();
its easy like this. you can get process by name, id etc. just go to your process, Kill(), and WaitForExit();
Upvotes: 3
Reputation: 137128
This answer assumes that you are launching Excel via Process.Start
. The code wasn't posted until later.
In that case keep hold of the process handle returned by that call and then use that to call Process.CloseMainWindow
followed by Process.Close
:
Process ExcelProcess; // Declaration
Store the process handle:
ExcelProcess = Process.Start(...);
Then when you exit your application:
// Close process by sending a close message to its main window.
ExcelProcess.CloseMainWindow();
// Free resources associated with process.
ExcelProcess.Close();
Upvotes: 2
Reputation: 54724
How are you reading the Excel file? If you're using COM, you need to call Application.Quit
when you're finished.
Edit: from the code in your comment -
//Initializing the application class
ApplicationClass appClass = new ApplicationClass();
try
{
Workbook workBook = appClass.Workbooks.Open(path,0,true,5,"","",true,XlPlatform.xlWindows,"\t",false,false,0,true,1,0);
Worksheet workSheet = (Worksheet)workBook.ActiveSheet;
// do stuff with the workbook
}
finally
{
appClass.Quit();
}
Upvotes: 9
Reputation: 4342
Instead of killing the processes... why don't you dispose your Excel-handles correctly instead? Sounds like you open instances of Excel without ever closing them properly. It's generally a good idea to also release acquired resources after using them.
Upvotes: 5
Reputation: 7326
Check out this example - http://www.dreamincode.net/code/snippet1543.htm
It uses the Process.Kill() method - http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx
Upvotes: 2