简体   繁体   English

无法创建MemoryStream

[英]Can't create MemoryStream

Is there any reason why this code shouldn't produce a memory stream with the word Slappy in it? 是否有任何原因为什么此代码不应产生其中包含单词Slappy的内存流?

    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()); 即使我说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. 但是无论如何,即使我调用上面的方法,从有效的方法中,输出仍然是空的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.Write的调用之后添加以下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 : 此外,如果您想稍后从内存流中读取该单词,请确保重置其位置,因为在Write之后,它位于slappy单词slappy

memoryStream.Position = 0;

If you don't want to call streamWriter.Flush(); 如果您不想调用streamWriter.Flush(); you can set the AutoFlush-Property of the StreamWriter, at the moment you create it. 您可以在创建时设置StreamWriter的AutoFlush-Property。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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