无法创建MemoryStream [英] Can't create MemoryStream

查看:82
本文介绍了无法创建MemoryStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么没有任何理由使此代码不产生带有单词Slappy的内存流?

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;
    }

即使我说streamWriter.Write(source.toString());,它也会失败.

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.

但是无论如何,即使我调用了上面的方法,从有效的方法中,输出仍然是一个空的MemoryStream.

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

有什么想法吗?

推荐答案

您不刷新流写入器,因此永远不会将单词写入内存流.

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

在调用streamWriter.Write之后添加以下内容:

Add the following after the call to streamWriter.Write:

streamWriter.Flush();

此外,如果您想稍后从内存流中读取该单词,请确保重置其位置,因为在写入"之后它位于单词slappy之后:

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;

这篇关于无法创建MemoryStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆