How to add encoding information to the response stream in ASP.NET? How to add encoding information to the response stream in ASP.NET? asp.net asp.net

How to add encoding information to the response stream in ASP.NET?


I ran into the same problem, and this was my solution:

context.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());context.Response.Write("ąęćżźń󳥌ŻŹĆŃŁÓĘ");


What you call "encoding-information" is actually a BOM. I suspect each of those "characters" is getting encoded separately. To write the BOM manually, you have to write it as three bytes, not three characters. I'm not familiar with the .NET I/O classes, but there should be a method available to you that takes a byte or byte[] parameter and writes them directly to the file.

By the way, the UTF-8 BOM is optional; in fact, its use is discouraged by the Unicode Consortium. If you don't have a specific reason for using it, save yourself some hassle and leave it out.

EDIT: I just remembered you can also write the actual BOM character, '\uFEFF', and let the encoder handle it:

context.Response.Write('\uFEFF');


I think the problem is with Excel based on Microsoft Excel mangles Diacritics in .csv files. To prove this, copy your sample output string of ąęćżźń󳥌ŻŹĆŃŁÓĘ and paste into a test file using your favorite editor, and save as a UTF-8 encoded .csv file. Open in Excel and see the same issues.