C#通过using语句创建流对象

时间:2017-03-25 20:09:07

标签: c# asp.net-mvc amazon-s3 io

我有一种下载s3文件的方法

方法

Public ActionResult download(string filename, string credentials)
{
  ....
  Using(stream res = response from s3)
  { 
       return file(res, type, filename);
   }
}

但例外是抛出执行上述方法。

  

异常消息 - 请求已中止:连接意外关闭

我必须在下载后释放流'res'对象。

1 个答案:

答案 0 :(得分:1)

如果使用File方法返回ActionResult,则转移责任将关闭流的操作结果,所以你确实想要致电Dispose或使用using。这样ActionResult不需要缓冲数据。所以:只需取出using

public ActionResult Download(string filename, string credentials)
{
  ....
  var res = /* response from s3 */
  return File(res, type, filename);
}

如果你有非平凡的代码,你可以使它更复杂:

public ActionResult Download(string filename, string credentials)
{
  ....
  Stream disposeMe = null;
  try {
      // ...
      disposeMe = /* response from s3 */
      // ...
      var result = File(disposeMe, type, filename);    
      disposeMe = null; // successfully created File result which
                        // now owns the stream, so *leave stream open*
      return result;
  } finally {
      disposeMe?.Dispose(); // if not handed over, dispose
  }
}