在 c# 中的列表中获取两行不同的 StreamReader 行之间的行

Fetching lines between two different line of StreamReader in a List in c#

我有一个 StreamReader reader我的内容如下

some text here
Test text here
TEST_START,,,,,,
Test,1,text
Test,2,text
Test,3,text
Test,4,text
Test,5,text

TEST_STOP,,,,,,
some text here

我需要在代码下方使用的 list.I 中获取 TEST_STARTTEST_STOP 之间的行,但不知道我错过了什么
Reference 取自此处:

string start_token = "TEST_START";
string end_token = "TEST_STOP";
string line;
bool inCorrectSection = false;    
while ((line = reader.ReadLine()) != null)
{
    if (line.StartsWith(start_token))
    {
        if (inCorrectSection)
        {
            break;
        }
        else if(line.StartsWith(end_token))
        {                           
            inCorrectSection = true;
        }
    }
    else if (inCorrectSection)
        myList.Add(line);
}

看起来你只需要稍微改变一下逻辑:

  1. 找到起始行后,将变量设置为 true(并继续循环)。
  2. 当您找到结束行时,将您的变量设置为 false(并继续循环,或者如果您只希望捕获一个部分,则中断循环)。
  3. 如果您的变量为真,则捕获行

例如:

while ((line = reader.ReadLine()) != null)
{
    if (line.StartsWith(start_token))
    {
        // We found our start line, so set "correct section" variable to true
        inCorrectSection = true;
        continue;
    }

    if (line.StartsWith(end_token))
    {                           
        // We found our end line, so set "correct section" variable to false
        inCorrectSection = false;
        continue; // Change this to 'break' if you don't expect to capture more sections
    }

    if (inCorrectSection)
    {
        // We're in the correct section, so capture this line
        myList.Add(line);
    }
}