Asp.Net MVC 5 FileResult always download file with ANSI encoding

1.6k Views Asked by At

I have this part of code

Response.Charset = _encodingcode;
Response.AddHeader("Content-Encoding", _encodingcode);
Response.HeaderEncoding = Encoding.GetEncoding(_encodingcode);
Response.ContentEncoding = Encoding.GetEncoding(_encodingcode);
Response.ContentType = mimeType;                     

return File(_filedata, mimeType, $"{id}{_extension}");

But always when download the file the notepad's encoding is ANSI

2

There are 2 best solutions below

0
pakeha_by On

Notepad receives only _filedata bytes which are saved to disk as file with name specified in 3rd parameter, but neither mimeType nor any element of response header or body, that why specifying encoding has no effect.

You can give a hint to Notepad about some encodings by adding Byte Order Mark (BOM) at the beginning of you bytes stream:

  • For UTF-8 - 0xEF,0xBB,0xBF
  • For UTF-16/32 - 0xFF, 0xFE

Apart from that, there is no way to tell Notepad what encoding it should use.

0
Jin Thakur On

By default every encoding is ANSI if you provide improper text in encoding it goes as ANSI. Right way to change use

Context.Response.Charset = Encoding.UTF8.WebName;

If you want utf8 do this

 Encoding encoding = Encoding.UTF8;
     StreamWriter writer = new StreamWriter("Encoding.html", false, encoding);

     writer.WriteLine("<html><head>");

     // Write charset attribute to the html file.
     // The value of charset is returned by the WebName property.
     writer.WriteLine("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=" +
                           encoding.WebName +"\">");

         writer.WriteLine("</head><body>");
     writer.WriteLine("<p>" + HttpUtility.HtmlEncode(encoding.EncodingName) + "</p>");
     writer.WriteLine("</body></html>");
     writer.Flush();
     writer.Close();