using
DSkinTheme;
using
System;
using
System.Collections.Generic;
using
System.Data;
using
System.Diagnostics;
using
System.Linq;
using
System.Text;
using
System.Text.RegularExpressions;
using
System.Threading.Tasks;
namespace
ConsoleApp2
{
public
class
Program
{
static
void
Main(
string
[] args)
{
Console.Write(
"请输入端口号:"
);
string
port = Console.ReadLine();
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
;
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[1].EndsWith(
":"
port))
{
Console.WriteLine(
"8002端口的进程ID:{0}"
, arr[4]);
new
Program().KillProcess(Int32.Parse(arr[4]));
}
}
}
}
public
void
KillProcess(
int
processName)
{
try
{
Process thisproc = Process.GetProcessById(processName);
Console.WriteLine(
"进程名字为:"
thisproc.ProcessName);
if
(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
Console.WriteLine(
"进程 {0}关闭成功"
, processName);
}
catch
{
Console.WriteLine(
"结束进程{0}出错!"
, processName);
}
finally
{
Console.ReadKey();
}
}
}
}