Kill Process Excel C#

Eriksson picture Eriksson · Feb 16, 2012 · Viewed 40.4k times · Source

I have to 2 process excel. For example:

1) example1.xlsx 2) example2.xlsx

How to kill first "example1.xlsx"?

I use this code:

   foreach (Process clsProcess in Process.GetProcesses())
     if (clsProcess.ProcessName.Equals("EXCEL"))  //Process Excel?
          clsProcess.Kill();

That kill a both. I wanna kill just one... Thank you.

Answer

Ta01 picture Ta01 · Feb 16, 2012

The ProcessMainWindow Title will do it for you, it appends "Microsoft Excel - " to the name of the file:

So essentially (quick code):

private void KillSpecificExcelFileProcess(string excelFileName)
    {
        var processes = from p in Process.GetProcessesByName("EXCEL")
                        select p;

        foreach (var process in processes)
        {
            if (process.MainWindowTitle == "Microsoft Excel - " + excelFileName)
                process.Kill();
        }
    }

Use:

KillSpecificExcelFileProcess("example1.xlsx");

Edit: Tested and verified to work.