title: How to use recursion to parse text into a tree structure?
body: <p>I am new to C# and I am completely stuck on a parsing issue where I want to use recursion but my attempts to do so have gotten me nowhere. </p>
  
  <p>I want to read in a file that has the following format:</p>
  
  <pre><code>root:
     fileA
     sub1:
        fileB
        fileC
        sub2:
           fileD
           fileE
        fileF
     fileG
     sub3:
        fileH
  </code></pre>
  
  <p>Essentially, the lines ending the colons (:) are supposed to represent directories and the lines that do not end in colons are supposed to represent files in their parent directory as such: <strong>fileA</strong> and <strong>fileG</strong> belong in the <em>root</em> directory, <strong>fileB</strong>, <strong>fileC</strong>, and <strong>fileF</strong> are located within the <em>sub1</em> directory, and so on (location is determined by indents/spaces). </p>
  
  <p>Thus, I want to read in this file, and more complex files with a similar structure in a better way than I am currently doing it (a horrendous mess of for loops and if statements). I am using simple custom classes for the directories and files (I am not using .NET classes except for StreamReader for reading in the text file line by line) </p>
  
  <p>I have done something similar in python once but for some reason I cannot wrap my head around how to do it in C#, which is silly since this is an abstract problem and the language specific implementations should not matter that much. I guess what does matter is my lack of understanding of how to best apply recursion in situations like these. Am I on the right track? I just sense that there is a much more elegant way of parsing  this file into my self defined classes (retaining a tree structure in the sample text) and I think recursion is the answer. I just cannot see it. </p>
  
  <p>Any help would be appreciated, even if it is less an answer and more a violent shove in the right direction. Or a gentle nudge. </p>
  
  <p>Sample Code in C# trying to use Recursion (incomplete, but I hope it gets across what I am trying to do):</p>
  
  <pre><code>public void buildDirectoryFromFile(string file)
  {
      string line;
      StreamReader data = new StreamReader(file);           
  
      int depth = 0;
      while ((line = data.ReadLine()) != null)
      {
          depth = line.Length - line.TrimStart(' ').Length;
          parseTextIntoTree(line, depth);
      }            
  }  
  
  
  public void parseTextIntoTree(string line, int depth)
  {    
     if (line.Contains(':'))
     {
        //Totally lost      
     }
     else
     {
         //Totally lost
     }         
  }  
  </code></pre>
  
  <p>Depth in this case refers to the spaces/indents. The more spaces there are between the string and the left margin the 'deeper' it is in the tree. </p>