2

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!

2
  • You need to reset the seek origin of the stream before using it to save/prompt user: stackoverflow.com/questions/1121703/… Commented Nov 7, 2014 at 3:56
  • 1
    @Papa i don't have any memorystream object. Commented Nov 7, 2014 at 4:06

1 Answer 1

2

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); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.