Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在MVC2中将流作为附件发送到浏览器_C#_Asp.net Mvc 2 - Fatal编程技术网

C# 在MVC2中将流作为附件发送到浏览器

C# 在MVC2中将流作为附件发送到浏览器,c#,asp.net-mvc-2,C#,Asp.net Mvc 2,我正在尝试为MVC2中的开放式XML Excel电子表格实现一个文件下载链接。如果我直接写信给回复,它的工作原理如下 var data = MooseMartAdoManager.ExecuteSet("Report.StagAllCasesFullDetail"); var str = ExcelExportManager.GenerateSpreadsheet(data) as MemoryStream; Response.ContentType = "a

我正在尝试为MVC2中的开放式XML Excel电子表格实现一个文件下载链接。如果我直接写信给回复,它的工作原理如下

var data = MooseMartAdoManager.ExecuteSet("Report.StagAllCasesFullDetail");
         var str = ExcelExportManager.GenerateSpreadsheet(data) as MemoryStream;
         Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
         Response.AddHeader(
            "content-disposition",
            "attachment;filename=StagFullDetail" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".xlsx");
         str.WriteTo(Response.OutputStream);
但是,鉴于我已经花了时间来抽象所有关于如何收集数据的逻辑,以及如何为代码重用和IOC创建报告,如果能够弄清楚为什么这样做是可行的,那就太好了

  public FileStreamResult GetExcelDetailExport()
  {
     var data = MooseMartAdoManager.ExecuteSet("Report.StagAllCasesFullDetail");
     var file = ExcelExportManager.GenerateSpreadsheet(data);

     return File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 
        "StagFullDetail" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".xlsx");
  }
我得到的是txt格式的零字节文件


那么“正确”的MVC处理方法是什么呢?

您可能会遇到此问题的一个原因是
文件位于流的末尾:

var file = ExcelExportManager.GenerateSpreadsheet(data); // it is at the end of stream
我建议您设置为0:

file.Position = 0;
由于使用了忽略当前位置的
str.WriteTo
,因此以前的代码可以正常工作