Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill Process Excel C#

Tags:

c#

process

kill

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.

like image 695
Eriksson Avatar asked Feb 16 '12 17:02

Eriksson


1 Answers

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.

like image 112
Ta01 Avatar answered Oct 07 '22 04:10

Ta01