The downloaded file as stream in controller (ASP.N

2020-03-25 06:00发布

问题:

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

回答1:

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