Can't create MemoryStream

纵饮孤独 提交于 2019-12-13 18:15:22

问题


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?


回答1:


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;



回答2:


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
   }


来源:https://stackoverflow.com/questions/16140109/cant-create-memorystream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!