Search code examples
c#liststreamreader

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


I have a StreamReader readerwhere i have content as below

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

I need to fetch the lines between TEST_START and TEST_STOP in a list.I used below code but don't know i missed something
Reference taken from here:

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

Solution

  • It looks like you just need to change the logic slightly:

    1. When you find the start line, set your variable to true (and continue the loop).
    2. When you find the end line, set your variable to false (and continue the loop, or break the loop if you only expect to have one section to capture).
    3. If your variable is true, capture the line

    For example:

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