1

I have a library that uses StreamWriter to write a string into a Stream. I need it to write that string into a NOT FILE stream like MemoryStream. But when I try to read from that MemoryStream using a StreamReader I get an "Stream was not readable" error. Can anyone help?

The code is something like this:

        var stream = new MemoryStream();
        using (var sw = new StreamWriter(stream))
            sw.Write("hello");
        using (var sr = new StreamReader(stream))
            MessageBox.Show(sr.ReadToEnd());

The library code is:

    public void Save(Stream jsonStream)
    {
        if (jTokenValue == null)
        {
            return;
        }

        using (var streamWriter = new StreamWriter(jsonStream))
        {
            streamWriter.Write(jTokenValue.ToString());
        }
    }
Kamran Kia
  • 347
  • 3
  • 7
  • 4
    I'll give you a hint: when you have `using (var sw = new StreamWriter(stream))`, as soon as that `using` closes, it will close the stream writer, which *closes the underlying stream* unless you tell it not to. See https://stackoverflow.com/questions/2666888/is-there-any-way-to-close-a-streamwriter-without-closing-its-basestream –  Jan 08 '20 at 18:40
  • 1
    As @Amy commented code you have closes the stream and linked as duplicate question explains what can be done about it. I'd strongly recommend to rethink `Save(Stream)` method - if you expect implementations to use `StreamWriter` it would be better to start with `Save(StreamWriter)` otherwise you continue running into this "operation on disposed object" error all the time when one writes (or "fixes") code with regular `using(StreamWriter …)` logic. – Alexei Levenkov Jan 08 '20 at 18:47
  • Added a better duplicate for the context – Steve Jan 08 '20 at 18:48
  • public static void Demo() { var stream = new MemoryStream(); var sw = new StreamWriter(stream, Encoding.UTF8); sw.Write("hello"); sw.Flush(); stream.Position = 0; using (var sr = new StreamReader(stream)) { System.Console.WriteLine(sr.ReadToEnd()); } } – divyang4481 Jan 08 '20 at 19:05

0 Answers0