Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export file with correct encoding

I don't understand what is missing here. I am trying to export a file in csv format with extended ASCII characters like ÿ or ü but all i get is �
Do I need to specify something else in the response?

Encoding encoding = Encoding.UTF8;

//ToCSV writes the string correctly
var bytes = encoding.GetBytes("write ÿ or ü please");
MemoryStream stream = new MemoryStream(bytes);

StreamReader reader = new StreamReader(stream);
//TextWriter tw = new TextWriter();
Response.Clear();
Response.Buffer = true;

Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName));
Response.Charset = encoding.EncodingName;
Response.ContentType = "application/text";
Response.Output.Write(reader.ReadToEnd());
Response.Flush();
Response.End();
like image 213
kiev Avatar asked Apr 08 '11 03:04

kiev


People also ask

How do I save a file with encoding?

To save a file with encodingFrom the File menu, choose Save File As, and then click the drop-down button next to the Save button. The Advanced Save Options dialog box is displayed. Under Encoding, select the encoding to use for the file. Optionally, under Line endings, select the format for end-of-line characters.

How do I know if a CSV file is UTF-8 encoded?

On Windows computers - the easiest way to do this is as follows: Open the file using Notepad. Click "File > Save As". In the dialog window that appears - select "UTF-8" from the "Encoding" field.


2 Answers

I believe you should add Response.ContentEncoding = Encoding.Unicode to get right output.

    Encoding encoding = Encoding.UTF8;
    var bytes = encoding.GetBytes("write ÿ or ü please");
    MemoryStream stream = new MemoryStream(bytes);
    StreamReader reader = new StreamReader(stream);
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", "filename"));
    Response.Charset = encoding.EncodingName;
    Response.ContentType = "application/text";
    Response.ContentEncoding = Encoding.Unicode;
    Response.Output.Write(reader.ReadToEnd());
    Response.Flush();
    Response.End();
like image 94
Özgür Kaplan Avatar answered Sep 24 '22 01:09

Özgür Kaplan


Unfortunately Encoding.Unicode didn't work, using Windows-1252 worked :

Response.Clear();
Response.ContentType = "Application/x-msexcel";
Response.AddHeader("content-disposition", "attachment; filename=\"filename.csv\"");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("Windows-1252");
Response.Write(string.Join(Environment.NewLine, myDataLines));
Response.End();
like image 40
Chtiwi Malek Avatar answered Sep 26 '22 01:09

Chtiwi Malek