You should always track opened word and excel applications to close them when your application exits.
This is the code to release the word or excel application. This is for word application but change and use it for excel applications :
wordApplication.Quit(SaveChanges: false, OriginalFormat: false, RouteDocument: false);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplication);
If your application was crashed and you didn't have the chance to close the excel or word application you should use this special code :
Helper class :
public static class ProcessExtension
{
private static string FindIndexedProcessName(int pid)
{
try
{
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;
for (var index = 0; index < processesByName.Length; index++)
{
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int)processId.NextValue() == pid)
{
return processIndexdName;
}
}
return processIndexdName;
}
catch
{
return "";
}
}
private static Process FindPidFromIndexedProcessName(string indexedProcessName)
{
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
try
{
return Process.GetProcessById((int)parentId.NextValue());
}
catch
{
return null;
}
}
public static Process Parent(this Process process)
{
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}
Some parts of this code were extracted from stackoverflow.
And use it by this way :
Process parentProcess;
foreach (var process in Process.GetProcesses().Where(i => i.ProcessName == "WINWORD"))
{
parentProcess = process.Parent();
if ((parentProcess != null) && (string.Compare(parentProcess.ProcessName, "svchost", true) == 0))
{
process.Kill();
}
}
This will kill all WORD processes which their parent is
svchost
.
If user starts an excel or word application its parent will be
explorer
.
Change it so that it can kill excel processes.
Hope it helps.