public static void StopProcess()
{
string port = "5000";
Process pro = new Process();
// 设置命令行、参数
pro.StartInfo.FileName = "cmd.exe";
pro.StartInfo.UseShellExecute = false;
pro.StartInfo.RedirectStandardInput = true;
pro.StartInfo.RedirectStandardOutput = true;
pro.StartInfo.RedirectStandardError = true;
pro.StartInfo.CreateNoWindow = true;
// 启动CMD
pro.Start();
// 运行端口检查命令
pro.StandardInput.WriteLine("netstat -ano");
pro.StandardInput.WriteLine("exit");
// 获取结果
Regex reg = new Regex(@"\s ", RegexOptions.Compiled);
string line = null;
while ((line = pro.StandardOutput.ReadLine()) != null)
{
line = line.Trim();
if (line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
{
line = reg.Replace(line, ",");
string[] arr = line.Split(',');
if (arr[2].EndsWith(":" + port))
{
KillProcess(Int32.Parse(arr[13]));
}
}
}
}
public static void KillProcess(int processName) //调用方法,传参
{
try
{
// // Process[] thisproc = Process.GetProcessesByName(processName);
Process thisproc = Process.GetProcessById(processName);
if (!thisproc.CloseMainWindow()) //尝试关闭进程 释放资源
{
thisproc.Kill(); //强制关闭
}
}
catch //出现异常,表明 kill 进程失败
{
}
finally
{
}
}
网友评论