Search code examples
asp.net-corestringbuilder

.NET Core - StringBuilder - missing character in downloaded file


I export some data to a csv on an angular/.NET Core app

a ; is missing after the first csv field, while the other ; are there

and the instructions used are the same for the other fields

StringBuilder sb = new StringBuilder();
sb.Append("Id; Civility;Name; Email; Phone;");
sb.Append("\r\n");

for (int i = 0; i < partners.Count; i++)
{
    Partner p = partners[i];
    sb.Append('"' + p.Id + '"' + ';');

    sb.Append('"' +(p.Manager.Civility==0?"Mr":"Mme") +'"'+ ';');
    sb.Append('"' + p.Manager.FirstName+" "+ p.Manager.LastName + '"' + ';');
    ...

here is the part that sends it to the web client for download

DateTime localDate = DateTime.Now;
var date = localDate.ToString("MM_dd_yy_HH_mm_ss");

var filename = "Partners_" + date + ".csv";
Response.Headers.Add("x-file-name", filename);
Response.Headers.Add("Access-Control-Expose-Headers", "x-file-name");
return File(Encoding.UTF8.GetBytes(sb.ToString()), "text/csv", filename);
  • why is the ; missing in the data ?
  • apparently the quotes are missing too for the id field

enter image description here

thanks for your time on this


Solution

  • This happens because adding up an int with a char yields an int as result.

    var x = 'a' + 5; 
    //yields 102 as 'a' is implicitly cast from char to int, where 'a' holds the value of 97
    

    You can fix it by either converting the int to a string by using ToString() or you can use strings instead of chars e.g.

    sb.Append("\"" + p.Id + "\";"); //the " is escaped using \