In an MVC application I have an action that exports data to CSV files. The code looks like this:
public ActionResult CSV(int id)
{
var model = GetRaportData(id); // Gets the data that will be exported
var cd = new System.Net.Mime.ContentDisposition
{
FileName = model.Raport.Name + ".csv",
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
// The contents of the CSV file are rendered via a view
var csv = ViewToString.RenderRazorViewToString(ControllerContext, "_CSV", model);
// To make the CSV file compatible with encoding in Excel
// the file is reencoded in Ansi 1250
return File(csv.ToAnsi1250(), "text/plain");
}
I presume the problem is related to this piece of code:
var cd = new System.Net.Mime.ContentDisposition
{
FileName = model.Raport.Name + ".csv",
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
Whenever I try to save a file that has UTF-8 characters (namely polish characters) in the name and the file name has certain length (or more), this "%0d%0a" string will show up in the name of the saved file at some point.
For instance:
Ę This file has a very long name Lorem Ipsum Lorem Ipsum.csv
becomes
Ę This file has a very long name Lorem Ip%0d%0a sum Lorem Ipsum.csv
It doesn't appear to matter where the UTF-8 character is located, what character it is or how many of them are there.
If there are no UTF-8 characters in the name or the name is relatively short, "%0d%0a" will not appear in the saved file name.
Anyone got a clue why does this happen and\or how to fix it?
Edit: If I name my file:
ABThis file has a very long name Lorem Ipsum Lorem Ipsum.csv
the problem will not occur.
I could possibly remove UTF-8 characters by replacing them with basic latin ones, but I would rather try to fix the problem, than use a workaround.
As suggested by Ricardo Momm, I tested the problem in a different browser (the description above describes how it looked in FireFox). In Chrome, the files that would get "%0d%0a" injected in their name in FireFox, just get renamed to "16" with no extension.
Edit: The "16" came from url that was leading to the file (something like http://someaddress/CSV/16
), so it appears Chrome was ignoring the name completely.