如何从FileStreamResult获取内容

时间:2014-11-07 03:20:08

标签: c# asp.net-mvc

我正在使用第三方库,其中一个方法返回FileStreamResult

public FileStreamResult GenerateFile(OutFormat format, dynamic params);

我的控制器中的操作调用此方法:

public ActionResult GenerateExcel()
{
    Utils.XCore core = new Utils.XCore(...); // where ... are contructor params
    // ... other codes here ...
    return core.GenerateFile(OutFormat.EXCEL, new { FileName = "Report" });
}

这样会好的,但有时我想将多个Excel工作表合并为一个,如下所示:

public ActionResult GenerateExcel()
{
    Utils.XCore core = new Utils.XCore(...); // where ... are contructor params
    // ... other codes here ...
    var excel1 = core.GenerateFile(OutFormat.EXCEL, new { FileName = "rpt1" });
    var excel2 = core.GenerateFile(OutFormat.EXCEL, new { FileName = "rpt2" });
    var excel3 = core.GenerateFile(OutFormat.EXCEL, new { FileName = "rpt3" });

    var finalContent = combineFile(excel1, excel2, excel3);

    return new FileStreamResult(finalContent, "application/ms-excel")
       {
           FileDownloadName = "Report.xls"
       };
}

我现在的问题是我不知道如何从FileStreamResult获取内容。关于如何做的任何想法?甚至包含网站链接的评论也非常受欢迎。谢谢!

1 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,您希望处理/获取FileStreamResult中的内容。该类包含一个名为FileStream的属性,它是一个Stream对象。现在,流对象现在可以使用以下修改后的代码from this site保存为文件:

private void streamToFile(Stream fileStream, string filePath)
{
    using (FileStream writeStream = new FileStream(filePath, 
                                    FileMode.Create, 
                                    FileAccess.Write))
    {
        int length = 1024;
        Byte[] buffer = new Byte[length];
        int bytesRead = fileStream.Read(buffer, 0, length);
        while (bytesRead > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
            bytesRead = fileStream.Read(buffer, 0, length);
        }
        fileStream.Close();
        writeStream.Close();
    }
}

以下是如何使用:

var excel1 = core.GenerateFile(OutFormat.EXCEL, new { FileName = "rpt1" });
string filePath = "C:\\yourFileName.xls"; // path of your newly saved file 
using (Stream reportStream = excel1.FileStream)
{
     streamToFile(reportStream, filePath);
}