如何在C#中实现去除netstat命令输出内容的表头行
完全可以通过C#实现该需求,核心思路是通过C#调用netstat命令捕获标准输出,再对输出内容做行过滤即可。
完整实现代码
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; class NetstatOutputParser { static void Main() { List<string> resultRows = new List<string>(); // 配置进程启动参数,执行netstat命令,-ano参数可显示PID信息,可根据需求调整参数 ProcessStartInfo startInfo = new ProcessStartInfo("netstat", "-ano") { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; using (Process process = Process.Start(startInfo)) { using (StreamReader reader = process.StandardOutput) { string line; bool isHeaderEnd = false; while ((line = reader.ReadLine()) != null) { // 跳过所有空行 if (string.IsNullOrWhiteSpace(line)) continue; // 匹配到Proto开头的表头行,标记表头结束,跳过该行 if (line.StartsWith("Proto")) { isHeaderEnd = true; continue; } // 表头结束后的数据行加入结果集 if (isHeaderEnd) { resultRows.Add(line); } } } process.WaitForExit(); } // 测试输出过滤后的结果 foreach (string row in resultRows) { Console.WriteLine(row); } } }
方案说明
- 上述代码采用表头匹配的方式做过滤,而非固定跳过前N行,适配性更强:不同Windows版本、不同语言环境下
netstat输出的表头前空行数量可能存在差异,匹配Proto开头的表头行可以兼容各类情况 - 如果你确认运行环境固定,也可以采用固定行数跳过的简化写法,替换读取行的逻辑即可:
int skipLineCount = 3; // 1行Active Connections + 1行空行 + 1行Proto表头,共跳过3行 int currentLineIndex = 0; while ((line = reader.ReadLine()) != null) { currentLineIndex++; if (currentLineIndex <= skipLineCount) continue; if (!string.IsNullOrWhiteSpace(line)) { resultRows.Add(line); } }
注意事项
- 读取部分系统端口的连接信息需要管理员权限,程序运行异常时可尝试以管理员身份启动
- 后续如果需要拆分每行的协议、本地地址、远程地址、状态、PID字段,可以通过正则匹配或者按多空格分割字符串的方式做进一步解析
内容的提问来源于stack exchange,提问作者Akash Kumar
相关产品推荐
相关产品推荐

