0

My application is a .net WebAPI (C#, without MVC), that apart from other things, has to server some csv files whose content can also include non standard characters (i.e. Greek Letters).

I tried finding a solution on SO but most answers involved using the File method of the base mvc controller class (which I don't have access to).

My current code is shown below (I've even removed the File.ReadAllText part, to check if it can just return a simple Hello World Text).

private HttpResponseMessage GetFile(string fileName)
{
    var response = new HttpResponseMessage();
    try
    {
        response.Content = new StringContent("Γειά σου Κόσμε");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName + ".csv" };
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
    }
    catch (Exception) { response.Content = new StringContent("File does not exist"); }
    return response;
}

I've also tried using response.Content.Headers.ContentEncoding.Add(Encoding.UTF8.BodyName);

Some weird interactions:

If I download the file and open it using Excel it just reads gibberish, if I open using notepad++ the text reads just fine. It also states that the encoding is utf8, if I change it to utf-8 BOM and the save the file, excel can read it.

If I simply move the file from the server to my computer, excel has no problem reading it.

nick zoum
  • 7,216
  • 7
  • 36
  • 80
  • try `new StringContent("Γειά σου Κόσμε", Encoding.UTF8, "text/csv")` – aepot Aug 05 '20 at 20:32
  • @aepot There's no difference. I believe the problem lies in the difference between utf8 and utf8bom. But I'm not sure how to set it to bom. – nick zoum Aug 05 '20 at 20:40
  • Compare byte by byte response and copied file. – aepot Aug 05 '20 at 20:41
  • Possible duplicate of [Is it possible to force Excel recognize UTF-8 CSV files automatically?](https://stackoverflow.com/q/6002256/11683) – GSerg Aug 05 '20 at 20:42
  • 1
    @aepot thank you for the help. I managed to find the answer in a question about an MVC project after all. – nick zoum Aug 05 '20 at 20:55

1 Answers1

1

It seems I had overlooked a question. It was about an MVC project but the answer still applies.

I just had to change it to:

var content = Encoding.UTF8.GetBytes(File.ReadAllText(pathName));
response.Content = new ByteArrayContent(Encoding.UTF8.GetPreamble().Concat(content).ToArray());

It seems I was missing the characters that are supposed to appear at the start of the utf8bom files.

nick zoum
  • 7,216
  • 7
  • 36
  • 80