using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace HTEXKiller { class Program { /// /// kill指定端口的PID进程。 /// /// static void Main(string[] args) { int port = 9527; 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 list_pid = GetPidByPort(p, port); List 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("是否要结束这些进程?"); Console.WriteLine(sb); PidKill(p, list_pid); Console.ReadLine(); } private static void PidKill(Process p, List 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 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 list_pid = new List(); StringBuilder sb = new StringBuilder(); while (!reader.EndOfStream) { strLine = strLine.Trim(); if (strLine.Length > 0 && ((strLine.Contains("TCP") || strLine.Contains("UDP")))) { Regex r = new Regex(@"\s+"); string[] strArr = r.Split(strLine); for (int i = 2; i < strArr.Length; i++) { b = int.TryParse(strArr[i], out result); if (b && !list_pid.Contains(result)) list_pid.Add(result); } } strLine = reader.ReadLine(); sb.Append(strLine); } p.WaitForExit(); reader.Close(); p.Close(); return list_pid; } private static List GetProcessNameByPid(Process p, List list_pid) { p.Start(); List list_process = new List(); StreamReader reader = null; foreach (var pid in list_pid) { p.StandardInput.WriteLine(string.Format("tasklist |find \"{0}\"", pid)); p.StandardInput.WriteLine("exit"); reader = p.StandardOutput;//截取输出流 string strLine = reader.ReadLine();//每次读取一行 while (!reader.EndOfStream) { strLine = strLine.Trim(); if (strLine.Length > 0 && ((strLine.Contains(".exe")))) { Regex r = new Regex(@"\s+"); string[] strArr = r.Split(strLine); if (strArr.Length > 0) { list_process.Add(strArr[0]); } } strLine = reader.ReadLine(); } p.WaitForExit(); } if (reader != null) { reader.Close(); } p.Close(); return list_process; } } }