使用FileStreamResult,MemoryStream是如何关闭的?

时间:2012-05-02 17:17:58

标签: .net asp.net-mvc-3 memorystream filestreamresult

以下代码有效,但我想知道创建的MemoryStream是否已正确关闭。该如何执行或FileStreamResult为我处理它?<​​/ p>

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

2 个答案:

答案 0 :(得分:38)

FileStreamResult会为您做到这一点。如果有疑问总是检查代码,因为代码永远不会出现,因为ASP.NET MVC是开源的,所以查看代码更加容易。

在Google上快速搜索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);
        }
    }
}

答案 1 :(得分: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;
    }
  }
}