随着FileStreamResult,如何将MemoryStream关闭?(With FileStr

2019-06-24 03:14发布

下面的代码工作,但如果我想知道MemoryStream创建正确关闭。 如何来执行或不FileStreamResult处理一下吗?

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;
}

Answer 1:

FileStreamResult会为你做的。 如有疑问经常检查代码,因为代码永远不会撒谎,因为ASP.NET MVC是开放源代码查看代码它更容易。

对于FileStreamResult.cs在谷歌快速搜索,您可以验证在WriteFile方法的流是使用正确设置using的语句。 (没有双关语意)

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);
        }
    }
}


Answer 2:

您可以访问源代码,所以你可以检查自己;-)

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;
    }
  }
}


文章来源: With FileStreamResult, how is the MemoryStream closed?