First off, I am using my own Process Wrapper to hold the starting path of a process.
public class MCProcess()
{
public Process Process { get; set;}
public string StartingPath { get; set;}
public MCProcess(string start, Process p)
{
Process = p;
StartingPath = start;
}
}
Now, I keep have a List<MCProcces> called runningProcesses that I use to keep track of all the processes and starting paths of every process that my program has started.
For Example:
string path = "C:\\Windows\\System32\\notepad.exe";
Process temp = Process.Start(path);
runningProcesses.Add(new MCProcess(path, temp));
Now, sometimes, I want to close processes that I have run. Instead of looking through the task manager and trying to find the MainModuleName of each process that I started, I included the StartingPath for a reason.
If I want to close a notepad, I just loop through my runningProcesses, find out which process has the startingPath for notepad and then use Process.Kill to kill that process.
string path = "C:\\Windows\\System32\\notepad.exe";
for (int i = 0; i < runningProcesses.Count; i++)
{
if (runningProcesses[i].StartingPath == path)
{
runningProcesses[i].Process.Kill();
runningProcesses.RemoveAt(i);
}
}
This code works beautiful on Windows 7 and I have had no issues at all. However, when using this on Windows XP, I get an ArgumentNullException with Process.Kill.
Is there something about the Process class that doesn’t make it work well on Windows XP?
Amazed how this is working in win 7. You are modifying a collection while using it in loop. You should maintain index of processes to be deleted, and then once done with the loop, remove all the processes
Try something like