So then we come to why the issue shows up? "Ive debugged and can see the data from the database is being shown correctly but when i export it to the response, the special characters come back as gobbledygook, even the pound symbol is coming back as '£'"
what do you do?
- Check the data in the database is stored correctly and it is getting to the response without being corrupted
- Check you are setting the ContentEncoding correctly, what do you need to use? UTF8 is always a good one to use if you are unsure
- Make sure you are using the right BOM (Byte Order Mark)! (this is nearly always the issue with unexplained chars with the correct encoding, see below
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// create csv data | |
StringBuilder builder = new StringBuilder(); | |
builder.AppendLine("CountryDesc, CountryChars\n"); | |
builder.AppendLine("make sure to cater for ç or maybe ë and ä, as well as ᧡é"); | |
// make a datestamp for the export filename | |
string exportDateTime = DateTime.Now.ToString("yyy.MM.dd.HH.mm"); | |
// create BOM chars for UTF-8 | |
byte[] charsetBOM = { 0xEF, 0xBB, 0xBF }; | |
// make sure we have a clean responce | |
Response.Clear(); | |
// set the content type | |
Response.ContentType = "text/csv"; | |
// make sure it is downloaded and uses our filename | |
Response.AppendHeader("Content-Disposition", string.Format("attachment; filename=\"export_{0}.csv\"", exportDateTime)); | |
// write BOM | |
Response.BinaryWrite(charsetBOM); | |
// write contents | |
Response.Write(builder.ToString()); | |
// finish the response | |
Response.End(); |