Lets say I have an Excel file named "DataSheet.xls" open. How can I kill that Excel file using c#?
off hand don't have the code as such. but generally, in the past i'd have used a couple of api calls to do this. first, you'd get the window handle (hWnd) and then you'd use the sendmessage api call with the wm_close parameter.
that's about all i can remember -it's been about 10 yrs since i had to do that kinda stuff, so the field may have changed since then :)
The Process
class would allow you to kill a process. You could inspect all running excel.exe processes, get the main window handle for the process, check whether the caption of that window contains the name of the XLS file and then kill the process for that window.
Otherwise you could use the Office COM classes to talk to Excel. This may also allow you to shut down open workbooks.
It's very likely that a single process will contain multiple open workbooks. Especially because Excel prefers to re-use an existing instance when opening files from Explorer, Outlook, etc. instead of creating a new process for each workbook.
Not to mention killing the process will require you to either 1) close the main window which will prompt if there's unsaved changes or 2) forcefully kill the process which will likely cause Excel to show its crash recovery options the next time you launch it.
The best course of action is to use the Excel COM API to close the workbooks. You can use the Marshal.GetActiveObject method to get a running instance of Excel and then refer to the Office developer reference for more information about how to close specific named workbooks without prompting.
using Excel = Microsoft.Office.Interop.Excel;
(...)
var app = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
// I have english excel, but another culture and need to use english culture to use excel calls...
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
app.Workbooks["DataSheet"].Close(false, false, false);