Cannot access a closed Stream with MemoryStream and StreamWriter

A StreamWriter will close the underlying stream when Dispose is called so if you try the following pattern you’ll receive a “Cannot access a closed Stream” error message.

        Using MS As New MemoryStream()
            Using SW As New StreamWriter(MS, System.Text.Encoding.UTF8)
                SW.Write("Hello")
            End Using

            Using SR As New StreamReader(MS, System.Text.Encoding.UTF8)
                Return SR.ReadToEnd()
            End Using
        End Using

To fix this, you need to find a way to use your StreamReader before calling the StreamWriter‘s Dispose (which End Using does). You also need to make sure that you reset the stream’s current Position to the beginning of the stream. And while I don’t think that a MemoryStream buffers I recommend calling Flush on the StreamWriter just in case.

        Using MS As New MemoryStream()
            Using SW As New StreamWriter(MS, System.Text.Encoding.UTF8)
                SW.Write("Hello")
                'Flush any buffers
                SW.Flush()

                'Reset the stream position
                MS.Position = 0

                'Create and use the StreamReader before calling the StreamWriter's Dispose()
                Using SR As New StreamReader(MS, System.Text.Encoding.UTF8)
                    Return SR.ReadToEnd()
                End Using
            End Using
        End Using

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.