title: Why do I have a million null characters at the end of my CSV file
body: <p>I am generating a CSV export of data on the fly. I do this by getting a hashset of items, then transforming them row for row and writing them to a MemoryStream, which in turn gets sent to the client as a FileResult. Problem is there is about a million NULL characters at the end of the file, I would guess the number of these characters is equal to the number of items in the hashset. But they're at the end of the file, not the end of each line.</p>
  
  <p>Anyways, the code is like such:</p>
  
  <p>The Controller method:</p>
  
  <pre><code>public ActionResult ExportList(ListExportModel model)
  {
    System.IO.MemoryStream ms = ls.ExportListToCsv(model,Server.MapPath("~/uploads"));
    return File(ms.GetBuffer(),"text/csv",model.MailingList.ListName + ".csv");
  }
  </code></pre>
  
  <p>The ExportListToCsv method</p>
  
  <pre><code>public MemoryStream ExportListToCsv(ListExportModel model, string folderpath)
  {
      MemoryStream stream = new MemoryStream();
      StreamWriter writer = new StreamWriter(stream);
  
      writer.WriteLine(string.Join(",", model.Columns));
      var data = GetListItemsFromCsv(model.ListId, folderpath);
  
      XmlDocument doc = new XmlDocument();
      // Parallel.ForEach(data, (li) =&gt;
      foreach (var li in data)
      {
          string line = "";
          foreach (var field in model.Columns)
          {
              doc.LoadXml(li.CustomFields);
              switch (field)
              {
                  //our standard fields
                      case "email":
                          line += li.Email + ",";
                          break;
                      case "tel":
                          line += li.Tel + ",";
                          break;
  
                      default:
                          line += (doc.SelectNodes("//" + field))[0].Value + ",";
                          break;
                  }
              }
  
              writer.WriteLine(line.TrimEnd(','));
          }
          writer.Flush();
          stream.Position = 0;
          return stream;
      }
  </code></pre>
  
  <p>And the file (all dummy data, no actual persons were harmed during the making of the screenshot):
  <img src="https://i.stack.imgur.com/aTdZS.png" alt="enter image description here"></p>
  
  <p>Note: I get the same results regardless of whether I use </p>
  
  <blockquote>
    <p>writer.Flush()</p>
  </blockquote>
  
  <p>and </p>
  
  <blockquote>
    <p>stream.Position = 0 </p>
  </blockquote>
  
  <p>or not</p>