With FileStreamResult, how is the MemoryStream closed?

故事扮演 提交于 2019-11-30 22:20:03

问题


The following code works, but I'm wondering if the MemoryStream created is closed properly. How should this be performed or does FileStreamResult handle it for me?

public FileStreamResult DownloadBudgetedRoleOpportunities(
    Guid projectGuid, 
    IEnumerable<Guid> guidRequiredRoles)
{
    var rolebroker = new ProjectRoleBudgetBroker();
    var memstream = rolebroker.CreateBudgetedRoleOpportunies(
        projectGuid, 
        guidRequiredRoles);

    var fsr = new FileStreamResult ( memstream, "application/csv" )
              {
                FileDownloadName = "RoleOpportunities.csv"
              };
    // memstream.Close(); throws exception
    return fsr;
}

回答1:


The FileStreamResult will do that for you. When in doubt always check the code, because the code never lies and since ASP.NET MVC is open source it's even more easy to view the code.

A quick search on Google for FileStreamResult.cs lets you verify that in the WriteFile method the stream is correctly disposed using the using statement. (no pun intended)

protected override void WriteFile(HttpResponseBase response) {
    // grab chunks of data and write to the output stream
    Stream outputStream = response.OutputStream;
    using (FileStream) {
        byte[] buffer = new byte[_bufferSize];

        while (true) {
            int bytesRead = FileStream.Read(buffer, 0, _bufferSize);
            if (bytesRead == 0) {
                // no more data
                break;
            }

            outputStream.Write(buffer, 0, bytesRead);
        }
    }
}



回答2:


You have access to source code, so you can check yourself ;-)

protected override void WriteFile(HttpResponseBase response)
{
  Stream outputStream = response.OutputStream;
  using (this.FileStream)
  {
    byte[] buffer = new byte[4096];
    while (true)
    {
      int count = this.FileStream.Read(buffer, 0, 4096);
      if (count != 0)
        outputStream.Write(buffer, 0, count);
      else
        break;
    }
  }
}


来源:https://stackoverflow.com/questions/10418594/with-filestreamresult-how-is-the-memorystream-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!