Linq probably isn't your best bet here. Just try doing

var lines = File.ReadAllLines(filename);
List<string> linesICareABout = new List<string>();
for(int i = 0; !linesICareAbout[i].Contains("part2=002"); ++i)

Then do whatever you want with the lines you read in.

However, if you're really dedicated to using Linq, try TakeWhile


The simplest and streghtforward solution comes to me is something like this:

var lines = File.ReadAllLines(@"C:\Sample.txt").

It returns result you want actually. The logic is simple:

  • SkipWhile lines till meeting a line that contains "part1"
  • after Skip(1) (as it will be actually that one that contains "part1" string)
  • finally Take those ones till getting to the line containing "part2".


public static IEnumerable<string> GetLinesBetween(
    string path,
    string fromInclusive,
    string toExclusive)
    return File.ReadLines(path)
        .SkipWhile(line => line != fromInclusive)
        .TakeWhile(line => line != toExclusive);

var path = Path.Combine(sExecPath, sFileName); // don't combine paths like that
var result = GetLinesBetween(path, "part1=001", "part2=002").ToList();


I think you are looking for TakeWhile:

var linesInPartOne = File
       .ReadAllLines(sExecPath + @"\" + sFileName)
       .SkipWhile(line => !line.StartsWith("**part1="))
       // To skip to part 1 header line, uncomment the line below:
       // Skip(1)
       .TakeWhile(line => !line.StartsWith("**part2="));

To generalize this to retrieve any given numbered part, something like this would do:

public static IEnumerable<String> ReadHeaderPart(String filePath, int part) {
    return File
        .SkipWhile(line => !line.StartsWith("**part" + part + "="))
        // To skip to part 1 header line, uncomment the line below:
        // Skip(1)
       .TakeWhile(line => 
            !line.StartsWith("**part" + (part + 1) + "=" 

EDIT: I had a Skip(1) in there to skip the part 1 header. Removed it since you seem to want to keep that line.

Related Query

More Query from same tag