一、在C#中判斷指定路徑的程序是否已經運行(不區分32/64位)
可以通過以下步驟實現:
獲取系統中所有進程
獲取每個進程的主模塊路徑
與目標路徑比較(忽略大小寫和路徑格式差異)
以下是完整代碼示例:
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
public class ProcessChecker
{
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 || ex is NotSupportedException)
{
continue;
}
finally
{
process.Dispose();
}
}
return false;
}
public static void Main()
{
string exePath = @"C:\Program Files\MyApp\MyProgram.exe";
bool isRunning = IsProcessRunning(exePath);
Console.WriteLine(isRunning
? $"程序已在運行: {exePath}"
: $"程序未運行: {exePath}");
}
}
關鍵點說明:
1、路徑規范化處理:
2、異常處理:
跳過系統/權限不足的進程(Win32Exception)
忽略已退出的進程(InvalidOperationException)
跳過非托管進程(NotSupportedException)
3、比較優化:
4、資源釋放:
注意事項:
需要管理員權限才能訪問所有進程信息
對于UWP/Store應用可能不適用
路徑比較時考慮到了不同格式(如長短路徑、大小寫)
支持32/64位混合環境
如果遇到權限問題,可在應用程序清單文件(app.manifest)中添加:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
二、如果此程序已經打開,則強制將此程序終止退出
代碼如下:
using System;
using System.Diagnostics;
using System.IO;
using System.ComponentModel;
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)
{
}
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);
found = true;
Console.WriteLine($"已終止進程: {process.ProcessName} (PID: {process.Id})");
}
}
catch (Win32Exception ex)
{
Console.WriteLine($"權限不足,無法終止進程 {process.ProcessName}: {ex.Message}");
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
Console.WriteLine($"終止進程 {process.ProcessName} 時出錯: {ex.Message}");
}
finally
{
process.Dispose();
}
}
if (!found)
{
Console.WriteLine($"未找到運行中的進程: {Path.GetFileName(targetPath)}");
}
}
public static void Main()
{
string exePath = @"C:\Program Files\MyApp\MyProgram.exe";
if (IsProcessRunning(exePath))
{
Console.WriteLine("程序正在運行,即將強制終止...");
KillProcessByPath(exePath);
if (!IsProcessRunning(exePath))
{
Console.WriteLine("程序已成功終止");
}
else
{
Console.WriteLine("程序終止失敗");
}
}
else
{
Console.WriteLine("程序未運行");
}
}
}
關鍵功能說明:
1、進程終止方法 KillProcessByPath()
:
2、增強的錯誤處理:
3、操作反饋:
顯示終止進程的名稱和PID
提供未找到進程的提示
包含權限錯誤的詳細說明
4、使用示例:
先檢查進程是否運行
終止后二次驗證確保操作成功
提供清晰的狀態反饋
使用注意事項:
1、管理員權限:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
沒有管理員權限可能無法終止系統進程或其他用戶進程
2、路徑規范:
支持長路徑和短路徑
自動處理路徑大小寫差異
兼容不同格式的路徑分隔符
3、特殊場景處理:
會終止所有匹配路徑的進程實例
處理進程樹(如需保留子進程需額外處理)
等待進程完全退出后再繼續執行
?4、替代方案建議(如果權限問題無法解決):
Process.GetProcessesByName("MyProgram")
.ToList()
.ForEach(p => p.Kill());
此代碼適用于需要強制終止指定應用程序的場景,如安裝/更新程序前的清理操作,或解決程序卡死問題。
該文章在 2025/6/2 16:55:50 編輯過