Smithy
Smithy

Reputation: 2190

c# MVC Illegal characters in path

I'm generating a CSV file and trying to send it down the wire using MVC but I keep getting the Illegal characters in path exception.

I've tried using different ways, like quoting the columns, changing \n to Environment.NewLine but the cause of the problem still eludes me.

Controller code:

string csv = "";
csv = "Name, Sales, Qty, Cost, Profit" + "\n";
foreach (var item in model.ReportResults.Items) {
    csv += item.ToCsv();
}

return File(csv, "text/csv", "myfile.csv");

ToCsv method:

internal string ToCsv() 
{
    return "" + Name + "" + "," + Sales.ToString() + "," + Qty.ToString() + "," + Cost.ToString() + "," + Profit.ToString() + "\n";
}

Snapshot of the CSV file that's generated:

Name, Sales, Qty, Cost, Profit
Tyranids,4979.29,182,3375.00,1604.29
Space Marines,2127.88,87,948.09,1179.79
Tau Empire,1584.01,40,0.00,1584.01
Eldar,1164.04,44,925.38,238.66
Imperial Guard,1005.79,34,790.10,215.69

Upvotes: 2

Views: 3036

Answers (1)

David
David

Reputation: 218847

You're using the wrong overload of File(). csv is a string, which tells it that you're looking for a file by that name. Naturally, the entirety of your CSV data isn't a valid filename, hence the error.

Instead of a string, you want to return a byte[] as the actual in-memory data of the "file." Perhaps something like this:

var csvBytes = Encoding.ASCII.GetBytes(csv);
return File(csvBytes, "text/csv", "myfile.csv");

(Or whatever character encoding you want to use.)

Upvotes: 10

Related Questions