Reputation: 7325
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.
Upvotes: 0
Views: 1728
Reputation: 7325
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.
Upvotes: 1