Cannot access a closed Stream while creating a downloadable text file in ASP MVC 3

前端 未结 4 733
臣服心动
臣服心动 2021-02-06 23:06

Im trying to prompt a downloadable text file (.txt), but I get this error:

Cannot access a closed Stream.

I have looked at simular q

4条回答
  •  被撕碎了的回忆
    2021-02-07 00:02

    That is correct, when you wrap a stream in another stream, calling .Close() or .Dispose() on any of them will dispose the whole stream. In this case, wrapping the MemoryStream in a StreamWriter means that when the using statement completes the StreamWriter and MemoryStream are both disposed.

    My guess is since you are returning a FileStreamResult the encapsulating File will close the stream for you after the stream is no longer used. In this case, you do not want to use the using statement and will want to leave the stream open when returning it.

    UPDATE

    Since a stream is forward access you'll need to see the stream back to the beginning to allow the data to be read back out.

    stream.Seek(0, SeekOrigin.Begin);
    

提交回复
热议问题