Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC - dispose resource in controller

What's the proper way of disposing resources when a method in the controller returns filestream or file or filecontentresult objects ?

For ex when doing something like below:

   using CrystalDecisions.CrystalReports.Engine;

public ActionResult Report()
{
    ReportClass rptH = new ReportClass();
    rptH.FileName = Server.MapPath("[reportName].rpt");
    rptH.Load();
    rptH.SetDataSource([datatable]);
    Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
    return File(stream, "application/pdf");   
}

TIA

like image 723
SoftwareGeek Avatar asked May 11 '10 16:05

SoftwareGeek


1 Answers

A FileStreamResult (which is what is created) wraps the stream in a using statement when WriteFile is called during result execution. This will close and dispose of the stream. Depending on the type of stream created it may actually cause an error to either close or wrap the usage in a using statement in the controller action.

like image 61
tvanfosson Avatar answered Nov 03 '22 00:11

tvanfosson