title: Using WriteAllText How To Write DataTable Column Names To CSV File
body: <p>I am new to C# and am using WriteAllText to write contents of a DataTable to a csv file.  Everything works as I expect <strong>EXCEPT</strong> the header information, which should be the DataTable column names.  </p>
  
  <p>How do I write the DataTable column names as my header?</p>
  
  <pre><code>private void GenerateRETest()
  {
      DataTable rI = new DataTable();
      rI.Columns.Add("sID", typeof(int));
      rI.Columns.Add("sn", typeof(string));
      rI.Columns.Add("RE", typeof(string));
      rI.Rows.Add(25, "Apex 1", "RE 1");
      rI.Rows.Add(50, "Apex 2", "RE 1");
      rI.Rows.Add(10, "Apex 3", "RE 1");
      rI.Rows.Add(21, "Apex 4", "RE 1");
      rI.Rows.Add(251, "Apex 11", "RE 11");
      rI.Rows.Add(501, "Apex 21", "RE 11");
      rI.Rows.Add(101, "Apex 31", "RE 11");
      rI.Rows.Add(211, "Apex 41", "RE 11");
      rI.Rows.Add(215, "Apex 12", "RE 12");
      rI.Rows.Add(510, "Apex 22", "RE 12");
      rI.Rows.Add(110, "Apex 32", "RE 12");
      rI.Rows.Add(211, "Apex 42", "RE 12");
  
      var columnNames = dt.AsEnumerable().GroupBy((sn) =&gt; sn.Field&lt;string&gt;("RE"))
                                          .Select((group) =&gt; new
                                          {
                                              RE = group.Key,
                                              DataRowList = group.OrderBy((dataRow) =&gt; dataRow.Field&lt;string&gt;("sn")).ToList()
                                          }).OrderBy(x =&gt; x.RE).ToList();
  
      foreach (var row in columnNames)
      {
          foreach (var dataRow in row.DataRowList)
          {
              StringBuilder sb = new StringBuilder();
              sb.AppendLine(string.Join(",", columnNames));
              IEnumerable&lt;string&gt; fields = dataRow.ItemArray.Select(field =&gt; string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
              sb.AppendLine(string.Join(",", fields));
          }
          string fileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)) + "\\" + row + "display.csv";
          File.WriteAllText(fileName, sb.ToString());
      }
  }
  </code></pre>