使用Response.TransmitFile下载文件但也包含页面源

时间:2011-12-20 02:58:32

标签: c# asp.net .net

以下是有问题的代码,我下载了一个csv,但它将页面源附加到底部有关如何防止这种情况的想法?

            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();

3 个答案:

答案 0 :(得分:4)

致电Response.End()

另外,为什么保存文件只是为了重新发送?充其量这是浪费,但如果你重复使用这个名字,那么如果有两个人同时点击这个页面你会遇到竞争条件。使用var csv = new CsvHelper.CsvHelper(Response.OutputStream)代替发送文件,这样您就可以直接写入浏览器了(虽然您必须先发送标题)。

此外,CSV文件的内容类型为text/csv

答案 1 :(得分:1)

刷新流后尝试添加Response.End()方法或尝试强制下载。

答案 2 :(得分:0)

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();