Search for a header and put that header in a list

Total Post:149


 1391  View(s)
Rate this:

I have a textfile with blogposts, each blogpost is divided in a header and content shown below


    A post        


    My content goes here...


    Another post


    My content goes here...

Now I want to grab all the headers, the text that comes after #Header and before #Content and put that in a List<>. How can I do that?

This is what I have come up with so far:

var headers = new List<string>();

using (StreamReader reader = new StreamReader(Path))


            string line;

            while ((line = reader.ReadLine()) != null)



                    .SkipWhile(l => l != "#Header")


                    .TakeWhile(l => !l.StartsWith("#"))




Linq is preferred.

  1. Re: Search for a header and put that header in a list

    Hi Royce,

    You can use regex with LINQ

    string contents = File.ReadAllText("yourTextFile.txt");

    List<string> header=Regex.Matches(contents,@"#Header\s*(.*?)\s*#",RegexOptions.IgnoreCase | RegexOptions.Singleline)




Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.