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

C# 在c中获取列表中两个不同StreamReader行之间的行#,c#,list,streamreader,C#,List,Streamreader,我有一个StreamReader阅读器,其中我有如下内容 这里的一些文本这里的测试文本测试开始,,,,,测试,1,文本测试,2,文本 测试,3,文本测试,4,文本测试,5,文本 测试停止,,,,,此处有一些文本 我需要在列表中获取TEST\u START和TEST\u STOP之间的行。我使用了下面的代码,但不知道我遗漏了从这里获取的内容: string start_token = "TEST_START"; string end_token = "TEST_STOP"; string line

我有一个StreamReader
阅读器
,其中我有如下内容

这里的一些文本
这里的测试文本
测试开始,,,,,
测试,1,文本
测试,2,文本
测试,3,文本
测试,4,文本
测试,5,文本

测试停止,,,,,
此处有一些文本

我需要在列表中获取
TEST\u START
TEST\u STOP
之间的行。我使用了下面的代码,但不知道我遗漏了从这里获取的内容:

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);
}

看起来您只需要稍微更改逻辑:

  • 找到起始行后,将变量设置为true(并继续循环)
  • 找到结束行后,将变量设置为false(并继续循环,如果只希望捕获一个部分,则中断循环)
  • 如果变量为true,则捕获该行
  • 例如:

    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);
        }
    }
    

    好的,那么你尝试了什么?你的问题是什么?你是要求我们为你写代码,还是你有一些代码来显示你试图解决问题的方法?请查看我更新的问题。谢谢你,鲁弗斯,工作正常。我能听到那些台词。