CouncilScribe
CouncilScribe

Reputation: 711

Using Response.TransmitFile to download file but also contains the page source

Below is the offending code, I download a csv however it appends the page source to the bottom any ideas on how to prevent this?

            var priceList = Test();
            const string downloadName = "PriceList.csv";
            var fs = new FileStream(downloadName, FileMode.Create);

            var csv = new CsvHelper.CsvHelper(fs);
            csv.Writer.WriteRecords(priceList);
            Response.ClearContent();

            //not sure what the correct content type is. This is probally wrong
            Response.ContentType = "application/xls";
            //Setting size is optional               
            Response.AddHeader("Content-Disposition",
               "attachment; filename=" + downloadName + "; size=" + fs.Length.ToString());
            var fn = fs.Name;
            fs.Close();
            loadingImage.Visible = false;
            Response.TransmitFile(fn);
            Response.Flush();

Upvotes: 3

Views: 5721

Answers (3)

Jon Hanna
Jon Hanna

Reputation: 113392

Call Response.End().

Also, why save the file just to resend it? At best this is wasteful, but also if you're reusing the name then you've a race-condition if two people hit this page at the same time. Instead of sending the file, use var csv = new CsvHelper.CsvHelper(Response.OutputStream) so you write straight to the browser (you'll have to send your headers first though).

Also, the content-type for CSV files is text/csv.

Upvotes: 4

Pencho Ilchev
Pencho Ilchev

Reputation: 3241

var priceList = Test();
        const string downloadName = "PriceList.csv";
        var fs = new FileStream(downloadName, FileMode.Create);

        var csv = new CsvHelper.CsvHelper(fs);
        csv.Writer.WriteRecords(priceList);
        Response.ClearContent();

        //not sure what the correct content type is. This is probally wrong
        Response.ContentType = "application/xls";
        //Setting size is optional               
        Response.AddHeader("Content-Disposition",
           "attachment; filename=" + downloadName + "; size=" + fs.Length.ToString());
        var fn = fs.Name;
        fs.Close();
        loadingImage.Visible = false;
        Response.TransmitFile(fn);
        Response.Flush();
        Response.End();

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94653

Add Response.End() method after you flush the stream or try force-download.

Upvotes: 1

Related Questions