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;
}

猜你喜欢

转载自blog.csdn.net/qq_38463737/article/details/121503816
今日推荐