简体   繁体   中英

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?

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;

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
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM