using System;
using System.Diagnostics;
using System.IO;
using System.ComponentModel; // 用于Win32Exception
public class ProcessManager
{
public static bool IsProcessRunning(string targetPath)
{
string fullTargetPath = Path.GetFullPath(targetPath).TrimEnd('\\');
foreach (var process in Process.GetProcesses())
{
try
{
if (process.MainModule == null) continue;
string processPath = Path.GetFullPath(process.MainModule.FileName).TrimEnd('\\');
if (string.Equals(processPath, fullTargetPath, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
catch (Exception ex) when (ex is Win32Exception || ex is InvalidOperationException)
{
// 跳過無權(quán)限訪問的進(jìn)程
}
finally
{
process.Dispose();
}
}
return false;
}
public static void KillProcessByPath(string targetPath)
{
string fullTargetPath = Path.GetFullPath(targetPath).TrimEnd('\\');
bool found = false;
foreach (var process in Process.GetProcesses())
{
try
{
if (process.MainModule == null) continue;
string processPath = Path.GetFullPath(process.MainModule.FileName).TrimEnd('\\');
if (string.Equals(processPath, fullTargetPath, StringComparison.OrdinalIgnoreCase))
{
process.Kill();
process.WaitForExit(3000); // 等待最多3秒
found = true;
Console.WriteLine($"已終止進(jìn)程: {process.ProcessName} (PID: {process.Id})");
}
}
catch (Win32Exception ex)
{
Console.WriteLine($"權(quán)限不足,無法終止進(jìn)程 {process.ProcessName}: {ex.Message}");
}
catch (InvalidOperationException)
{
// 進(jìn)程已退出,忽略
}
catch (Exception ex)
{
Console.WriteLine($"終止進(jìn)程 {process.ProcessName} 時(shí)出錯(cuò): {ex.Message}");
}
finally
{
process.Dispose();
}
}
if (!found)
{
Console.WriteLine($"未找到運(yùn)行中的進(jìn)程: {Path.GetFileName(targetPath)}");
}
}
// 使用示例
public static void Main()
{
string exePath = @"C:\Program Files\MyApp\MyProgram.exe";
if (IsProcessRunning(exePath))
{
Console.WriteLine("程序正在運(yùn)行,即將強(qiáng)制終止...");
KillProcessByPath(exePath);
// 二次驗(yàn)證
if (!IsProcessRunning(exePath))
{
Console.WriteLine("程序已成功終止");
}
else
{
Console.WriteLine("程序終止失敗");
}
}
else
{
Console.WriteLine("程序未運(yùn)行");
}
}
}