I generate on-the-fly CSV data export. I do this by getting a hash of the elements and then converting them to a string for a string and writing them to a MemoryStream, which in turn is sent to the client as a FileResult. The problem is that at the end of the file there are about a million NULL characters, I would assume that the number of these characters is equal to the number of elements in the hash set. But they are at the end of the file, not at the end of each line.
In any case, the code is:
Controller Method:
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");
}
ExportListToCsv Method
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();
foreach (var li in data)
{
string line = "";
foreach (var field in model.Columns)
{
doc.LoadXml(li.CustomFields);
switch (field)
{
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;
}
And the file (all fictitious data, no actual faces were affected during the creation of the screenshot):

Note. I get the same results whether I use
writer.Flush ()
and
stream.Position = 0
Or no