Home > DeveloperSection > Forums > Search for a header and put that header in a list
Royce Roy
Royce Roy

Total Post:134

Posted on    March-29-2014 4:17 AM

 C# C# 

 1 Reply(s)
 798  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.

Pravesh Singh

Total Post:411

Posted on    March-29-2014 7:04 AM

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)



Don't want to miss updates? Please click the below button!

Follow MindStick