C#实现查询某个端口是被哪个程序进程占用


C#实现查询某个端口是被哪个程序进程占用

C#执行DOS命令匹配获取指定端口被哪个进程 占用

        /// <summary>
        /// 执行dos命令脚本
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public string ExecCMD(string command)
        {
            System.Diagnostics.Process pro = new System.Diagnostics.Process();
            pro.StartInfo.FileName = "cmd.exe";
            pro.StartInfo.UseShellExecute = false;
            pro.StartInfo.RedirectStandardError = true;
            pro.StartInfo.RedirectStandardInput = true;
            pro.StartInfo.RedirectStandardOutput = true;
            pro.StartInfo.CreateNoWindow = true;
            //pro.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            pro.Start();
            pro.StandardInput.WriteLine(command);
            pro.StandardInput.WriteLine("exit");
            pro.StandardInput.AutoFlush = true;
            //获取cmd窗口的输出信息
            string output = pro.StandardOutput.ReadToEnd();
            pro.WaitForExit();//等待程序执行完退出进程
            pro.Close();
            return output;

        }

        /// <summary>
        /// 获取占用端口的进程
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public Process UsePortWithProcess(int port)
        {
            try
            {
                ///执行多事获取端口信息
                string cmd_response = ExecCMD("netstat -ano");
                byte[] txt = System.Text.UTF8Encoding.UTF8.GetBytes(cmd_response.ToCharArray());
                using (Stream readStream = new MemoryStream(txt))
                {
                    readStream.Position = 0;
                    using (StreamReader reader = new StreamReader(readStream))
                    {
                        ///正则表达式 用于提取信息
                        Regex reg = new Regex(" \\s+ ", RegexOptions.Compiled);
                        string line = null;
                        while ((line = reader.ReadLine()) != null)
                        {
                            line = line.Trim();
                            ///提取需要的端口相关信息行
                            if (line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
                            {
                                line = reg.Replace(line, ",");
                                string[] arr = line.Split(',');
                                if (arr[1].EndsWith($":{port}"))
                                {
                                    int pid = Int32.Parse(arr[4]);
                                    Process p = Process.GetProcessById(pid);
                                    return p;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex) { }
            return null;
        }

文章地址: C#实现查询某个端口是被哪个程序进程占用 | Yuan天空博客

相关内容