读取特定行之间的一行

时间:2014-08-19 12:56:21

标签: c# io

我有一个以这种方式构建的文本文件(文件的一部分):

          B                            NO        AMOUNT
            W                          10        200.00
            R                           1        110.00
            TOTAL                      11         90.00
                    111 TOTALS
          A                            NO        AMOUNT
            W                       4,159        640.00
            R                           0         00.00
            TOTAL                   4,159        640.00

          B                            NO        AMOUNT
            W                          10        200.00
            R                           1        110.00
            TOTAL                      11         90.00

                    222  TOTALS
          A                            NO        AMOUNT
            W                       4,000        510.00
            R                           0         10.00
            TOTAL                   4,000        500.00

我需要阅读以“TOTAL”开头>“111 TOTALS”和“222 TOTALS”之间的行。

我有以下代码来读取以“TOTAL”开头的行,我只是迷失在代码的方式/位置,我可以包含这个“介于”条件:

using System;
using System.IO;

public class TextFile4
{
  public static void ReadTextFile4()
  {
    int counter = 0;
    string line;

    //Find application path
    string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

    //Name of the file
    string filepath = dir + @"\Reports\abc.txt";

    // Read the file and display it line by line
    StreamReader file = new StreamReader(filepath);

    // Loop through text file
    while ((line = file.ReadLine()) != null)
    {
        if (line.Trim().StartsWith("TOTAL"))
        {
            Console.WriteLine(line);
        }
    counter++;
    }
    file.Close();
  }
}

可能搜索错误的内容,但找不到类似的主题。看到一些关于计算行数的主题,但它是这个文件中的一个变量,所以不是一个选项。

2 个答案:

答案 0 :(得分:2)

直到你遇到第一个条件才读取行,并在遇到第二个条件时停止。例如:

bool startFound= false;
while ((line = file.ReadLine()) != null)
    {
        var content = line.Trim();
        if (content.StartsWith("111 TOTALS")) 
        {
            startFound= true;
        }
        if (content.StartsWith("TOTAL") && startFound)
        {
            // this code is only called when the "111 TOTALS" was found
            // and the line starts with "TOTAL"
            Console.WriteLine(line);
        }
        if (content.StartsWith("222 TOTALS"))
        {
            // this will end the loop
            break;
        }
        counter++;
    }

此外,在处理流时使用using语句是个好主意。请参阅this article here了解如何使用它。

答案 1 :(得分:2)

这是必须使用的LINQ方法(未经测试):

string[] totalLines = File.ReadLines(filepath)
    .SkipWhile(l => !l.TrimStart().StartsWith("111 TOTALS"))
    .TakeWhile(l => !l.TrimStart().StartsWith("222  TOTALS"))
    .Where(l => l.TrimStart().StartsWith("TOTAL"))
    .ToArray();

结果:

        TOTAL                   4,159        640.00
        TOTAL                      11         90.00