gpt4 book ai didi

c# - 如何从 FileStreamResult 获取内容

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:01 24 4
gpt4 key购买 nike

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

public FileStreamResult GenerateFile(OutFormat format, dynamic params);

我的 Controller 中的一个 Action 调用了这个方法:

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 获取内容。关于如何做的任何想法?即使是包含网络链接的评论也非常受欢迎。谢谢!

最佳答案

如果我正确理解你的问题,你想处理/获取来自 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);
}

关于c# - 如何从 FileStreamResult 获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26793484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com