我如何杀死具有特定位置 C# 的进程 exe

How do I kill the process exe with a specific location C#

如果我在日志文件中发现错误并重新启动它,我有要求杀死一个exe。这里的主要问题是,我不能只根据名称删除 exe,因为我有来自不同文件夹的相同 exe 运行,例如 D:\A\A1.exe 和 D:\B\A1 。可执行程序。我只想从 "A" 文件夹中删除 exe。

我尝试遵循 Dirk Vollmar 的解决方案 ()。

这个问题 - C# Process Killing

但是,当我调试他的解决方案时,我发现 hModuleSnap 变量无效。

更新 - 1

正如 Micky 所建议的,我使用了 Simon's Answer。它确实杀死了 exe(谢谢)。但是,我收到一条错误消息 "System.ComponentModel.Win32Exception: Only part of a ReadProcessMemory or WriterocessMemory request was completed".

这是示例代码。

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();
        }

只需按照 Simon's answer 使用 ProcessModule.FileName。注意 FileName returns 完整路径,在 post.

中不明显

MSDN:

Gets the full path to the module. More...

原帖:

But, when I debug his solution, I found that hModuleSnap Variable is invalid.

你不应该要求这个。虽然 Dirk's answer 很好,但它相当冗长,我觉得过度使用了本机调用。

或者您可以使用我的简化版 Simon 的回答(同样没有本地调用):

注意:您必须运行以下代码提升

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();
    }
}

上面的例子没有围绕比较路径的子模块循环,因为 Process 已经有一个很好的 MainModule 属性 我们可以检查。

现在上面的例子并没有那么令人兴奋,但它确实允许你在你的计算机硬盘驱动器的各个部分中调用名为 kitty 运行ning 的进程).你可能有 c:\a\kitty.exed:\b\kitty.exe