I have a requirement of killing an exe if I find an error in the log file and restart it again. The main problem here is, I cannot just delete the exe based on the name as I have the same exe running from different folders, such as D:\\A\\A1.exe and D:\\B\\A1.exe. I only want to delete the exe from "A" folder.
I have tried to follow Dirk Vollmar's Solution ( https://stackoverflow.com/a/2238316/5159431 ).
to this question - C# Process Killing
But, when I debug his solution, I found that hModuleSnap Variable is invalid.
Update - 1
As Micky suggested, I have used Simon's Answer. It does kill the exe (Thanks for that). However, I am getting an error saying "System.ComponentModel.Win32Exception: Only part of a ReadProcessMemory or WriterocessMemory request was completed".
Here is the example code.
string path1 = @"F:\Software\Application\Runner.exe";
try
{
Process[] runningProcesses = Process.GetProcesses();
foreach (Process process in runningProcesses)
{
// now check the modules of the process
foreach (ProcessModule module in process.Modules)
{
if (module.FileName.Equals(path1))
{
process.Kill();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
Just use ProcessModule.FileName
as per Simon's answer . Note FileName
returns the full path, something that is not apparent in the post.
MSDN:
Gets the full path to the module. More...
OP:
But, when I debug his solution, I found that hModuleSnap Variable is invalid.
You shouldn't require this. Whilst Dirk's answer is fine, it's rather verbose and I feel makes excessive use of native calls.
Alternatively you can use my simplified version of Simon's answer (again no native calls):
NOTE: You must run the following code elevated
string targetProcessPath = @"c:\windows\system32\notepad.exe";
string targetProcessName = "notepad";
Process[] runningProcesses = Process.GetProcesses();
foreach (Process process in runningProcesses)
{
if (process.ProcessName == targetProcessName &&
process.MainModule != null &&
string.Compare(process.MainModule.FileName, targetProcessPath, StringComparison.InvariantCultureIgnoreCase)==0)
{
process.Kill();
}
}
The above example doesn't loop around the child modules comparing paths since Process
already has a nice MainModule
property that we can examine.
Now the above example isn't that thrilling but it does allow you to nuke processes called kitty running in various parts of your computer hard drive(s). You might have a c:\\a\\kitty.exe and d:\\b\\kitty.exe
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.