griegs
griegs

Reputation: 22760

Can't create MemoryStream

Is there any reason why this code shouldn't produce a memory stream with the word Slappy in it?

    private MemoryStream StringBuilderToMemoryStream(StringBuilder source)
    {
        MemoryStream memoryStream = new MemoryStream();
        StreamWriter streamWriter = new StreamWriter(memoryStream);
        streamWriter.Write("slappy");
        return memoryStream;
    }

Even if I say streamWriter.Write(source.toString()); it fails.

Funny thing is, that it works on one of the methods that calls this routine but not on any of the others.

And the order I call them in makes no difference either.

But regardless, even when I call the above, from the method that works, the output is still an empty MemoryStream.

Any thoughts?

Upvotes: 1

Views: 208

Answers (2)

Tomtom
Tomtom

Reputation: 9394

If you don't want to call streamWriter.Flush(); you can set the AutoFlush-Property of the StreamWriter, at the moment you create it.

MemoryStream memoryStream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(memoryStream)
   {
      AutoFlush = true
   }

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

You don't flush the stream writer so the word never gets written to the memory stream.

Add the following after the call to streamWriter.Write:

streamWriter.Flush();

Furthermore, if you want to read that word later from the memory stream, make sure to reset its position, because after the Write it is located after the word slappy:

memoryStream.Position = 0;

Upvotes: 8

Related Questions