C# 删除指定Windows端口的进程

C# 删除指定Windows端口的进程

命名空间

using System.Diagnostics;
using System.Text.RegularExpressions;
using System.IO;

思路是通过 cmd 的netstat 命令获取端口的所有进程号(通过解析字符串)。然后通过Process 进程对象获取进程。最后使用Processkill() 方法杀死进程

代码

public int kill_port(int port = 52001, string nodeName="node")
{
    int result = 0;
    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 == 0)
    {
        Console.WriteLine("没有进程");
        return result;
    }
    // 删除进程
    foreach(int pid in list_pid)
    {
        try
        {
			// 根据进程号获取进程对象
            Process localById = Process.GetProcessById(pid);
            if (localById != null)
            {
                // 如果单单只想删除指定端口,不知道运行的程序名称,可以修改这句程序
                if (localById.ProcessName.Contains(nodeName))
                {
                    Console.WriteLine("删除进程:" + pid);
                    localById.Kill();
                    result += 1;
                }

            }
        }
        catch
        {
            Console.WriteLine("进程不存在: " + pid);
        }
    }

    Console.WriteLine("操作完成");
    return result;

}


private List<int> GetPidByPort(Process p, int port)
{
    int result;
    bool b = true;

    List<int> list_pid = new List<int>();

    string str = string.Format("netstat -ano|find \"{0}\"", port);  //cmd命令
    p.Start();
    p.StandardInput.WriteLine(str + "&exit");
    StreamReader reader = p.StandardOutput;
    string strLine = reader.ReadLine();

    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);
            if (strArr.Length >= 4)
            {
                // 这行是重点,因为可能windows版本不一样,进程号的位置也不一样
                b = int.TryParse(strArr[strArr.Length - 1], out result);
                if (b && !list_pid.Contains(result))
                {
                      if (!list_pid.Contains(result))
                       {
                           list_pid.Add(result);
                       }
                }
            }
        }
        strLine = reader.ReadLine();
    }
    p.WaitForExit();
    reader.Close();
    p.Close();
    return list_pid;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值