美文网首页
C# 根据端口关闭线程

C# 根据端口关闭线程

作者: 在凌晨失了眠 | 来源:发表于2021-02-23 19:14 被阅读0次
    
            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
                {
    
                }
    
            }
    

    相关文章

      网友评论

          本文标题:C# 根据端口关闭线程

          本文链接:https://www.haomeiwen.com/subject/rfjtfltx.html