1

I use next code to generate .csv file from my logs table.

public ActionResult Index()
{
var records = loggingService.GetLogRecords(model.Since, model.For);

var mainSb = new StringBuilder();
mainSb.Append("Date,User name\n");

foreach (var logRecord in records)
{
    mainSb.Append(logRecord.Time.ToString("dd/MM/yyyy hh:mm:ss")).Append(",");
    mainSb.Append("\"").Append(logRecord.UserName ?? "").Append("\"").Append(",");
}
return File(Encoding.Unicode.GetBytes(mainSb.ToString()), "text/csv", string.Format("logs.csv"));
}

Usernames contains cyrillic chars, and when I open my .csv file - cyrillic chars is bad displayed. I tried to use UTF8 and UTF32 encodings too. Whan encoding should I use or what changes should I do?

David Levin
  • 6,573
  • 5
  • 48
  • 80

1 Answers1

14

You could use UTF-8 with preamble. Try like this at the end:

var data = Encoding.UTF8.GetBytes(mainSb.ToString());
var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
return File(result, "text/csv", "logs.csv");

Also you seem to be using \n which is not the correct new line separator on Windows and you don't seem to be appending new lines in your foreach loop, so everything will be on the same line resulting in invalid CSV file. Please, please, please, do not roll your own CSV parser.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • For string be encoded I remove chars ',' and '"' from them. Is it enough? And can helpers you linked in answer help to generate (not parse) .csv file? – David Levin Mar 04 '12 at 20:14
  • Excellent answer, thanks for mentioning this. I just used it successfully to get Scandinavian characters working as well. – MEMark Oct 05 '13 at 10:04