I have to 2 process excel. For example:
1) example1.xlsx 2) example2.xlsx
How to kill first \"example1.xlsx\"?
I use this code:
f
Try getting the main window title
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Equals("EXCEL")&& clsProcess.MainWindowTitle =="example")
{
clsProcess.CloseMainWindow();
break;
}
}
Use below logic to prevent Zombie Excel processes in Task Manager
List<int> GetAllExcelProcessID()
{
List<int> ProcessID = new List<int>();
if (currentExcelProcessID == -1)
{
List<System.Diagnostics.Process> currentExcelProcessList = System.Diagnostics.Process.GetProcessesByName("EXCEL").ToList();
foreach(var item in currentExcelProcessList)
{
ProcessID.Add(item.Id);
}
}
return ProcessID;
}
int GetApplicationExcelProcessID(List<int> ProcessID1, List<int> ProcessID2)
{
foreach(var processid in ProcessID2)
{
if (!ProcessID1.Contains(processid)) { currentExcelProcessID = processid; }
}
return currentExcelProcessID;
}
void KillExcel()
{
System.Diagnostics.Process process = System.Diagnostics.Process.GetProcessById(currentExcelProcessID);
process.Kill();
}
List<int> ProcessID1 = GetAllExcelProcessID();
excel = new Excel.Application();
List<int> ProcessID2 = GetAllExcelProcessID();
currentExcelProcessID = GetApplicationExcelProcessID(ProcessID1, ProcessID2);
You need to check file handles, that are opened by process and then kill it.
How to check which file handles process is holding: How do I get the list of open file handles by process in C#?
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Equals("EXCEL") && HasFileHandle(fileName, clsProcess))
{
clsProcess.Kill();
break;
}
}
just did a quick search on Google, try Process.MainWindowTitle()
to get the title of the Excel process, and decide which one is that you want to kill.
I am not sure about this method, but hope this will help:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.mainwindowtitle.aspx