下面是有问题的代码,我下载了一个 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();
最佳答案
调用 Response.End()
。
还有,为什么保存文件只是为了重新发送呢?充其量这是一种浪费,但如果您重复使用该名称,那么如果两个人同时点击此页面,您就会遇到竞争条件。不要发送文件,而是使用 var csv = new CsvHelper.CsvHelper(Response.OutputStream)
这样您就可以直接向浏览器写入内容(不过您必须先发送 header )。
此外,CSV 文件的内容类型是 text/csv
。
关于c# - 使用 Response.TransmitFile 下载文件但也包含页面源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8570269/