Reputation: 2594
I am using a third party library in which one of the methods returns FileStreamResult
.
public FileStreamResult GenerateFile(OutFormat format, dynamic params);
An action in my controller calls this method:
public ActionResult GenerateExcel()
{
Utils.XCore core = new Utils.XCore(...); // where ... are contructor params
// ... other codes here ...
return core.GenerateFile(OutFormat.EXCEL, new { FileName = "Report" });
}
This is going to be fine but sometimes I want to merge multiple Excel worksheets into one which is something like this:
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"
};
}
My problem now is I don't know how to get the content from FileStreamResult
. Any ideas on how to do it? Even comments containing weblinks are pretty much appreciated. Thanks!
Upvotes: 2
Views: 7827
Reputation: 263693
If I correctly understand your question, you want to process/get the content from FileStreamResult
. The class contains a property called FileStream
which is a Stream
object. Now, the stream object can now be saved as a file using the following modified code 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();
}
}
and the following is how to use:
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);
}
Upvotes: 2