stephen0403 2024-01-17 13:07 采纳率: 100%
浏览 24
已结题

C#下,如何获取端口的进程号后终止进程

做了个WinForm,想实现输入端口号,查询指定端口号的进程,然后终止进程。参照了网上的示例,读端口号结果,获取pid时发生错误

故障现象 如果指定为21 80 这样的端口,就会出现
System.ObjectDisposedException: 无法从已关闭的 TextReader 中读取。这个错误。

未占用的端口,运行结果正常。
22 这样的端口,又正常 提示为svchost.exe在占用。

请教各位应该如何解决。


    private static List<string> GetProcessNameByPid(Process p, List<int> list_pid)
            {
                p.Start();
                List<string> list_process = new List<string>();
                foreach (var pid in list_pid)
                {
                    p.StandardInput.WriteLine(string.Format("tasklist |find \"{0}\"", pid));
                    p.StandardInput.WriteLine("exit");
                    StreamReader reader = p.StandardOutput;//截取输出流
                    string strLine = reader.ReadLine();//每次读取一行
    
                    while (!reader.EndOfStream)
                    {
                        strLine = strLine.Trim();
                        if (strLine.Length > 0 && ((strLine.Contains(".exe"))))
                        {
                            Regex r = new Regex(@"\s+");
                            string[] strArr = r.Split(strLine);
                            if (strArr.Length > 0)
                            {
                                list_process.Add(strArr[0]);
                            }
                        }
                        strLine = reader.ReadLine();
                    }
                    p.WaitForExit();
                    reader.Close();
                }
                p.Close();
                return list_process;
            }

错误为:

  • 写回答

2条回答 默认 最新

  • 爱蹦跶的大A阿 新星创作者: 前端开发技术领域 2024-01-17 14:02
    关注

    获取进程 PID 后立即读取标准输出时,此时 cmd 命令可能还没有完全执行结束,所以标准输出流已经被关闭了,导致无法读取。
    可以在写入命令后加个短暂 Sleep,给命令一点执行时间:

    p.StandardInput.WriteLine(cmd); 
    Thread.Sleep(100); // 加个睡眠
    
    

    或者不立即读取标准输出,而是先WaitForExit,等待命令完全结束:

    p.StandardInput.WriteLine(cmd);
    p.WaitForExit(); 
    
    // 等待退出后再读取输出
    StreamReader reader = p.StandardOutput; 
    //...
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月26日
  • 已采纳回答 1月18日
  • 创建了问题 1月17日