0

I'm trying to create a CSV export for some data I have. Seems simple enough, and works beautifully in Firefox and Chrome, but in Internet Explorer I just get a message saying the file could not be downloaded. No other error messages, no break in Visual Studio, no debugging information that I can find.

Here's my code. Perhaps I'm doing something wrong?

public ActionResult ExportStudentsCSV(IEnumerable<Student> students) {
    MemoryStream output = new MemoryStream();
    StreamWriter writer = new StreamWriter(output, System.Text.Encoding.UTF8);
    writer.WriteLine("Username,Year Level,School Name,State,Date Joined");
    foreach (Student student in students) {
        writer.WriteLine(
                    "\"" + student.username
            + "\",\"" + student.year_level
            + "\",\"" + student.SchoolName
            + "\",\"" + student.state
            + "\",\"" + student.join_date
            + "\""
        );
    }
    writer.Flush();
    output.Seek(0, SeekOrigin.Begin);

    return File(output, "text/csv", "Students_" + DateTime.Now.ToShortDateString().Replace('/', '-') + ".csv");
}

And I'm calling this function in my controller with:

    return ExportStudentsCSV(model.StudentReport.StudentList);
death_au
  • 1,282
  • 2
  • 20
  • 41

3 Answers3

2

You may need to add a Content-Disposition header.

In your ExportStudentsCSV function, before returning:

var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "filename.csv";
Response.AddHeader("Content-Disposition", cd.ToString());

Or if you'd rather be brief about it (equivalent to above):

Response.AddHeader("Content-Disposition", "attachment;filename=filename.csv");
quentin-starin
  • 26,121
  • 7
  • 68
  • 86
  • This worked fine for IE, but now Chrome won't download because it's apparently receiving multiple Content-Disposition headers and won't allow it. – death_au Feb 27 '12 at 04:40
1

It may seem dodgy to be answering my own question, but I thought my experience may help someone. I did some more digging and found a completely alternate way of doing this using DataTables and a specific CsvActionResult which inherits from FileResult.
See this gist: https://gist.github.com/777376

death_au
  • 1,282
  • 2
  • 20
  • 41
  • If the connection was SSL, IE7 requires the Content-Length header to be set which is not set by File or FileContentResult. I believe MVC 3 and IIS 7 take care of this for you behind the scenes. But downloading a file on IIS 6 using IE7 causes problems when there is no Content-Length header over an SSL connection. – James May 25 '12 at 17:22
0

Probably has something to do with the Content-Type/Content-Dispositon because IE follows standards when it wants to.

Check out ASP MVC3 FileResult with accents + IE8 - bugged?

Community
  • 1
  • 1
Juan Ayala
  • 3,388
  • 2
  • 19
  • 24