如何用StreamReader定位指定行后读取后续行并提取单个目标表格数据
解决StreamReader读取指定性能统计表格的问题
问题分析
现有代码仅能定位到"Performance Stats:"行并打印,但无法读取后续表格内容,也无法从多个重复表格中筛选出单个目标表格。
解决方案1:读取第一个表格的后续20行
修改代码逻辑,在定位到目标行后,开启表格读取状态,连续读取并打印后续20行后终止循环,避免处理其他表格:
string pathToFile = @"\\host\c$\temp\logs\myPerformanceFile.txt"; using (var filestream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var streamReader = new StreamReader(filestream, Encoding.Default)) { string line; bool isReadingTable = false; int linesRead = 0; const int targetLines = 20; while ((line = streamReader.ReadLine()) != null) { if (line.Contains("Performance Stats:")) { Console.WriteLine(line); isReadingTable = true; linesRead = 0; continue; } if (isReadingTable) { Console.WriteLine(line); linesRead++; if (linesRead >= targetLines) { break; // 读取够行数后直接退出,不再处理后续内容 } } } }
解决方案2:读取指定序号的表格(比如第3个)
如果需要从5个表格中选取特定序号的表格,增加计数器筛选目标表格,同时跳过其他表格的内容以提升效率:
string pathToFile = @"\\host\c$\temp\logs\myPerformanceFile.txt"; using (var filestream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var streamReader = new StreamReader(filestream, Encoding.Default)) { string line; bool isReadingTable = false; int linesRead = 0; const int targetLines = 20; int tableCounter = 0; const int targetTable = 3; // 要提取的表格序号(从1开始) while ((line = streamReader.ReadLine()) != null) { if (line.Contains("Performance Stats:")) { tableCounter++; if (tableCounter == targetTable) { Console.WriteLine(line); isReadingTable = true; linesRead = 0; } else { // 跳过当前非目标表格的所有行 while ((line = streamReader.ReadLine()) != null && !line.Contains("Performance Stats:")) { // 空循环跳过内容 } continue; } } if (isReadingTable) { Console.WriteLine(line); linesRead++; if (linesRead >= targetLines) { break; } } } }
关键优化点
- 用
isReadingTable标记切换读取状态,无需逐个判断表格标题,简化逻辑 - 通过
linesRead计数控制读取行数,精准获取约20行表格内容 - 针对多表格场景,用
tableCounter筛选目标表格,跳过无关内容减少IO消耗 - 路径字符串添加
@符号避免转义错误,修正原代码的语法问题(缺失分号)
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

