在ASP.NET中将字符串下载为文件

时间:2011-09-11 13:42:55

标签: asp.net file download stream response

以下方法基于this question中的代码,在浏览器中显示了一个文件下载对话框,但是下载永远不会启动(它保持在0%):

protected void lnkExport_Click(object sender, EventArgs e) {
  var bytes = Encoding.ASCII.GetBytes(SelectRecords()); //Data to be downloaded
  Response.Clear();
  Response.ContentType = "application/vnd.ms-excel";
  Response.AddHeader("Content-Disposition", "attachment; filename=\"test.xls\"");
  using (var stream = new MemoryStream(bytes)) {
    Response.AddHeader("Content-Length", stream.Length.ToString());
    stream.WriteTo(Response.OutputStream);
  }
}

知道发生了什么事吗?

1 个答案:

答案 0 :(得分:3)

您的代码对我来说很好,但您可能想尝试将其添加为点击处理程序的最后一行:

Response.End();