Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write unicode string to csv in c#

I used following code to create csv file from unicode string:

context.Response.ContentType = "text/csv";
context.Response.ContentEncoding = System.Text.Encoding.Utf8;        
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fundName + ".csv");
context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());                

String output ="";        
output += "Name, callNumber" + "\n";
String output ="علی,34343555" + "\n";     
context.Response.Write(output);

The problem is unicode character that don't show correctly "علی".

Thanks for any guides. Regards Ali

like image 917
user1957880 Avatar asked Nov 02 '25 14:11

user1957880


2 Answers

I would rather use streamwriter to write unicode characters using UTF-8 Encoding. Snippet:

 using (StreamWriter sw = new StreamWriter(new FileStream("c:/Temp.csv", FileMode.Create), Encoding.UTF8))
            {
                    sw.WriteLine(string.Join(",", s));
            }
like image 93
Nikhil Agarwal Avatar answered Nov 05 '25 03:11

Nikhil Agarwal


A few problems with the code.

  • context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); writes the BOM for UTF-32 not UTF-8.

  • the output variable is defined twice.

I suggest trying this:

context.Response.ContentType = "text/csv";
context.Response.ContentEncoding = System.Text.Encoding.Utf8;        
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fundName + ".csv");

String output ="";        
output += "Name, callNumber" + "\n";
output +="علی,34343555" + "\n";     
context.Response.Write(output);
context.Response.End()
like image 34
Richard Schneider Avatar answered Nov 05 '25 05:11

Richard Schneider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!