private void t_btn_kill_Click(object sender, EventArgs e)
{
int port;
bool b = int.TryParse(t_txt_guardport.Text, out port);
if (!b)
{
MessageBox.Show("请输入正确的监听端口");
return;
}
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
List<int> list_pid = GetPidByPort(p, port);
if (list_pid.Count == )
{
MessageBox.Show("操作完成");
return;
}
List<string> list_process = GetProcessNameByPid(p, list_pid);
StringBuilder sb = new StringBuilder();
sb.AppendLine("占用" + port + "端口的进程有:");
foreach (var item in list_process)
{
sb.Append(item + "\r\n");
}
sb.AppendLine("是否要结束这些进程?"); if (MessageBox.Show(sb.ToString(), "系统提示", MessageBoxButtons.YesNo) == DialogResult.No)
return;
PidKill(p, list_pid);
MessageBox.Show("操作完成"); } private static void PidKill(Process p, List<int> list_pid)
{
p.Start();
foreach (var item in list_pid)
{
p.StandardInput.WriteLine("taskkill /pid " + item + " /f");
p.StandardInput.WriteLine("exit");
}
p.Close();
} private static List<int> GetPidByPort(Process p, int port)
{
int result;
bool b = true;
p.Start();
p.StandardInput.WriteLine(string.Format("netstat -ano|find \"{0}\"", port));
p.StandardInput.WriteLine("exit");
StreamReader reader = p.StandardOutput;
string strLine = reader.ReadLine();
List<int> list_pid = new List<int>();
while (!reader.EndOfStream)
{
strLine = strLine.Trim();
if (strLine.Length > && ((strLine.Contains("TCP") || strLine.Contains("UDP"))))
{
Regex r = new Regex(@"\s+");
string[] strArr = r.Split(strLine);
if (strArr.Length >= )
{
b = int.TryParse(strArr[], out result);
if (b && !list_pid.Contains(result))
list_pid.Add(result);
}
}
strLine = reader.ReadLine();
}
p.WaitForExit();
reader.Close();
p.Close();
return list_pid;
} private static List<string> GetProcessNameByPid(Process p, List<int> list_pid)
{
p.Start();
List<string> list_process = new List<string>();
foreach (var pid in list_pid)
{
p.StandardInput.WriteLine(string.Format("tasklist |find \"{0}\"", pid));
p.StandardInput.WriteLine("exit");
StreamReader reader = p.StandardOutput;//截取输出流
string strLine = reader.ReadLine();//每次读取一行 while (!reader.EndOfStream)
{
strLine = strLine.Trim();
if (strLine.Length > && ((strLine.Contains(".exe"))))
{
Regex r = new Regex(@"\s+");
string[] strArr = r.Split(strLine);
if (strArr.Length > )
{
list_process.Add(strArr[]);
}
}
strLine = reader.ReadLine();
}
p.WaitForExit();
reader.Close();
}
p.Close(); return list_process;
}
原文链接:C#一键显示及杀死占用端口号进程
参考文献:C#实现检查指定端口被哪个进程占用