Search code examples
c#asp.netasp.net-mvc

Does FileStreamResult close Stream?


My question is similar to this question: Does File() In asp.net mvc close the stream?

I have the follows in C# MVC 4.

FileStream fs = new FileStream(pathToFileOnDisk, FileMode.Open);
FileStreamResult fsResult = new FileStreamResult(fs, "Text");
return fsResult;

Will fs be closed automatically by FileStreamResult? thanks!


Solution

  • Yes. It uses a using block around the stream, and that ensures that the resource will dispose.

    Here is the internal implementation of the FileStreamResult WriteFile method:

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