title: Efficient way to write a lot of lines to a text file
body: <p>I started off doing something as follows:</p>
  
  <pre><code>using (TextWriter textWriter = new StreamWriter(filePath, append))
  {
      foreach (MyClassA myClassA in myClassAs)
      {
          textWriter.WriteLine(myIO.GetCharArray(myClassA));
  
          if (myClassA.MyClassBs != null)
              myClassA.MyClassBs.ToList()
                  .ForEach(myClassB =&gt;
                      textWriter.WriteLine(myIO.GetCharArray((myClassB)));
  
          if (myClassA.MyClassCs != null)
              myClassA.MyClassCs.ToList()
                  .ForEach(myClassC =&gt;
                      textWriter.WriteLine(myIO.GetCharArray(myClassC)));
      }
  }
  </code></pre>
  
  <p>This seemed pretty slow (~35 seconds for 35,000 lines).  </p>
  
  <p>Then I tried to follow the example <a href="http://blogs.msdn.com/b/fyuan/archive/2012/08/04/textwriter-writeline-string-object-in-less-memory-less-time.aspx" rel="noreferrer">here</a> to create a buffer, with the following code, but it didn't gain me anything.  I was still seeing times around 35 seconds.  Is there an error in how I implemented the buffer?</p>
  
  <pre><code>using (TextWriter textWriter = new StreamWriter(filePath, append))
  {
      char[] newLineChars = Environment.NewLine.ToCharArray();
      //Chunk through 10 lines at a time.
      int bufferSize = 500 * (RECORD_SIZE + newLineChars.Count());
      char[] buffer = new char[bufferSize];
      int recordLineSize = RECORD_SIZE + newLineChars.Count();
      int bufferIndex = 0;
  
      foreach (MyClassA myClassA in myClassAs)
      {
          IEnumerable&lt;IMyClass&gt; myClasses =
              new List&lt;IMyClass&gt; { myClassA }
                  .Union(myClassA.MyClassBs)
                  .Union(myClassA.MyClassCs);
  
          foreach (IMyClass myClass in myClasses)
          {
              Array.Copy(myIO.GetCharArray(myClass).Concat(newLineChars).ToArray(),
                  0, buffer, bufferIndex, recordLineSize);
  
              bufferIndex += recordLineSize;
  
              if (bufferIndex &gt;= bufferSize)
              {
                  textWriter.Write(buffer);
  
                  bufferIndex = 0;
              }
          }
      }
  
      if (bufferIndex &gt; 0)
          textWriter.Write(buffer);
  }
  </code></pre>
  
  <p>Is there a better way to accomplish this?</p>