With FileStreamResult, how is the MemoryStream closed?

后端 未结 2 1595
情深已故
情深已故 2021-01-07 16:16

The following code works, but I\'m wondering if the MemoryStream created is closed properly. How should this be performed or does FileStreamResult

2条回答
  •  不要未来只要你来
    2021-01-07 17:00

    The FileStreamResult will do that for you. When in doubt always check the code, because the code never lies and since ASP.NET MVC is open source it's even more easy to view the code.

    A quick search on Google for FileStreamResult.cs lets you verify that in the WriteFile method the stream is correctly disposed using the using statement. (no pun intended)

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

提交回复
热议问题