3

Let's assume the controller which download selected file:

 public FileResult Download( string f ) {

         Stream file = MyModel.DownloadFiles( f );

         return File( file, "application/octet-stream", (file as FileStream).Name );
 }

and MyModel contains

public static Stream DownloadFiles(string file){

   return new FileStream(file, FileMode.Open, FileAccess.Read);
}

If I use using keyword in controller then the exception will be thrown: Cannot access closed file.

Well, I want to be sure that downloaded file will be disposed (I don't know if is possible, how to do that) or not ?

Thanks

Snake Eyes
  • 16,287
  • 34
  • 113
  • 221

1 Answers1

14

Controller.File method uses FileStreamResult class inside, that already contains using keyword

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

https://github.com/ASP-NET-MVC/ASP.NET-Mvc-3/blob/master/mvc3/src/SystemWebMvc/Mvc/FileStreamResult.cs

Dmitriy Startsev
  • 1,442
  • 10
  • 19
  • If I make integration test on `DownloadFiles` then will fail. Why I cannot use dispose in model (because give me Cannot access closed file). – Snake Eyes Nov 07 '12 at 08:24
  • 1
    MVC ActionResult executes after you leave action method. FileStreamResult need stream to be open, because it reads from stream. So you shouldn't close a stream inside your action method. – Dmitriy Startsev Nov 07 '12 at 08:36