1
        Encoding utf8 = new UTF8Encoding(true);
        Byte[] bom = utf8.GetPreamble();
        //var fs = new FileStream(@".\UTF8Encoding.csv", FileMode.Create);
        var result = bom.Concat(report.Body).ToArray();
        //Stream stream = new MemoryStream(result);
        //fs.Write(result, 0, result.Length);
        //fs.Close();
        var fcr = new FileContentResult(result, "application/csv");
        fcr.FileDownloadName = "rep.csv";
        return fcr;ode here

when I use FileStream it goes well and I got the file with the encoding required (UTF8-BOM), but in my case, i need to use FileResult or FileContentResult, the issue is when I use one of them the file is encoded UTF8 without BOM

someone
  • 139
  • 1
  • 12

2 Answers2

1

Found a solution:

byte[] csvBytes = Encoding.Default.GetBytes(csvString);
UTF8Encoding utf8 = new UTF8Encoding(true);
byte[] bom = utf8.GetPreamble();
var result = bom.Concat(csvBytes).ToArray();
return new FileContentResult(result, MediaTypeHeaderValue.Parse("text/csv; charset=utf-8"));
Luca Ziegler
  • 3,236
  • 1
  • 22
  • 39
0

In a .NET 6 Razor page, the following, slightly simpler, code produces the CSV with the BOM. For me, having the BOM seems to help Excel display display the £ symbol correctly.

byte[] csvBytes = Encoding.UTF8.GetBytes(csvString);
byte[] bom = Encoding.UTF8.GetPreamble();
var result = bom.Concat(csvBytes).ToArray();
return File(result, "text/csv; charset=utf-8", "Filename.csv");
Alex Wingrove
  • 35
  • 1
  • 6