94 lines
3.1 KiB
C#
94 lines
3.1 KiB
C#
using System;
|
||
using System.Diagnostics;
|
||
using System.Linq;
|
||
|
||
namespace ToolLibrary
|
||
{
|
||
public static class PortProcessManager
|
||
{
|
||
/// <summary>
|
||
/// 获取指定端口占用的进程 PID
|
||
/// </summary>
|
||
/// <param name="port">指定的端口号</param>
|
||
/// <returns>占用端口的进程 PID,失败时返回 -1</returns>
|
||
public static int GetProcessIdByPort(int port)
|
||
{
|
||
try
|
||
{
|
||
// 使用 netstat 命令获取端口信息
|
||
var startInfo = new ProcessStartInfo
|
||
{
|
||
FileName = "netstat",
|
||
Arguments = $"-ano | findstr :{port}", // 查找指定端口的占用情况
|
||
RedirectStandardOutput = true,
|
||
UseShellExecute = false,
|
||
CreateNoWindow = true
|
||
};
|
||
|
||
using (var process = Process.Start(startInfo))
|
||
using (var reader = process.StandardOutput)
|
||
{
|
||
string output = reader.ReadToEnd();
|
||
if (!string.IsNullOrEmpty(output))
|
||
{
|
||
// 输出格式: TCP 0.0.0.0:2403 0.0.0.0:0 LISTENING 1234
|
||
var columns = output.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
||
if (columns.Length > 4)
|
||
{
|
||
int pid = int.Parse(columns[columns.Length - 1]); // 获取 PID
|
||
return pid;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.WriteLine("查询端口进程失败: " + ex.Message);
|
||
}
|
||
|
||
return -1; // 返回无效的 PID
|
||
}
|
||
|
||
/// <summary>
|
||
/// 根据 PID 杀死指定的进程
|
||
/// </summary>
|
||
/// <param name="pid">进程 ID</param>
|
||
/// <returns>是否成功杀死进程</returns>
|
||
public static bool KillProcessById(int pid)
|
||
{
|
||
try
|
||
{
|
||
var process = Process.GetProcessById(pid);
|
||
process.Kill();
|
||
Console.WriteLine($"进程 PID {pid} 已成功结束。");
|
||
return true;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.WriteLine("结束进程失败: " + ex.Message);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 查询端口占用的进程并杀死该进程
|
||
/// </summary>
|
||
/// <param name="port">指定的端口号</param>
|
||
/// <returns>是否成功杀死进程</returns>
|
||
public static bool KillProcessByPort(int port)
|
||
{
|
||
int pid = GetProcessIdByPort(port);
|
||
if (pid > 0)
|
||
{
|
||
return KillProcessById(pid);
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine($"端口 {port} 没有被占用或未找到相关进程。");
|
||
return false;
|
||
}
|
||
}
|
||
}
|
||
|
||
}
|