title: parsing multi sections of a text file C#
body: <p>First let me start by thanking you all for being part of this site, I have already gained so much helpful information from it. including some basic parsing of text files in to Arrays, but i now want to go a step further. </p>
  
  <p>I have a text file that looks some thing like this </p>
  
  <pre><code>Start Section 1 - foods
  
  apple  
  bannana  
  pear   
  pineapple  
  orange  
  
  end section 1
  
  Start section 2 - animals
  
  dog  
  cat  
  horse  
  cow  
  
  end section 2 
  </code></pre>
  
  <p>what I want to do is using a single read of the file copy the data from section 1 in to an array called "foods" and section 2 in to and array called "animals"</p>
  
  <p>now I can get it to work by using a new loop for each section, closing and reopening the file each time, looping till I find the section I want and creating the array. </p>
  
  <p>But I was thinking there must be a way to read each section in to a separate array in one go saving time. </p>
  
  <p>so my current code is </p>
  
  <pre><code>List&lt;string&gt; typel = new List&lt;string&gt;();  
  
  using (StreamReader reader = new StreamReader("types.txt")) // opens file using streamreader
          {
  
              string line; // reads line by line in to varible "line"
              while ((line = reader.ReadLine()) != null) // loops untill it reaches an empty line
              {
                  typel.Add(line); // adds the line to the list varible "typel"
                                 }
  
          }
  
          Console.WriteLine(typel[1]);  // test to see if list is beeing incremented
          string[] type = typel.ToArray(); //converts the list to a true array 
          Console.WriteLine(type.Length); // returns the number of elements of the array created. 
  </code></pre>
  
  <p>which is for a simple text file with no sections just list of values, using list seemed a good way to deal with unknown lengths of arrays. </p>
  
  <p>I was also wondering how to deal with the first value. </p>
  
  <p>for example if i do </p>
  
  <pre><code>while ((line = reader.ReadLine()) != Start Section 1 - foods)  
  {  
  }  
  while ((line = reader.ReadLine()) != end Section 1)   
  {  
  foods.Add(line);  
  }  
  ...  
  ....
  </code></pre>
  
  <p>I end up with the "start Section 1 - foods" as one of the array elements. I can remove it with code but is there an easy way to avoid this so only the list items get populated? </p>
  
  <p>Cheers and once again thanks for all the help. Its great to be getting back in to programming after many many years. </p>
  
  <p>Aaron</p>