33

以下代码有效,但我想知道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;
}
4

2 回答 2

42

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);
        }
    }
}
于 2012-05-03T10:53:11.563 回答
3

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

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;
    }
  }
}
于 2012-05-03T10:54:28.207 回答