Friday, November 21, 2014

Encoding issue when exporting linq data to CSV C#

Hi,

I had been generating export in csv format from C# Code.

I faced an issue where CSV content heading had some Currency symbols and those were perfectly getting displayed in CSV but when you open those in excel, it shows some corrupted symbols.

i managed to resolve it using below sequence of development tasks.

My Earlier Code

  byte[] Bytes = GetFileDataBytes(filename);
 return File(Bytes , "text/csv", "report-" + DateTime.Now.ToString("yyyy-MMM-dd") + ".csv");

My New Code

  byte[] Bytes = GetFileDataBytes(filename);
 var result = Encoding.UTF8.GetPreamble().Concat(Bytes).ToArray();
 return File(result , "text/csv", "report-" + DateTime.Now.ToString("yyyy-MMM-dd") + ".csv");

Using Above code, i managed to open csv in excel with all special characters in it. :)

Thanks,
Ujjwal