MemoryStream之谜

时间:2013-09-27 14:32:06

标签: c# stream

我有一些代码已停止工作。它本身并没有改变,但已经停止了工作。

它涉及使用内存流从应用程序外部导入一些文本数据并将其传递到应用程序,最终将文本转换为字符串。以下代码片段封装了该问题:

    [TestMethod]
    public void stuff()
    {
        using (var ms = new MemoryStream())
        {
            using (var sw = new StreamWriter(ms))
            {
                sw.Write("x,y,z"); //"x,y,z" is usually a line of string data from a textfile
                sw.Flush();
                stuff2(ms);
            }
        }

    }

    void stuff2(Stream ms)
    {
        using (var sr = new StreamReader(ms))
        {
            stuff3(sr.ReadToEnd());
        }

    }

    void stuff3(string text)
    {
        var x = text; //when we get here, 'text' is an empty string.
    }

我错过了什么吗? “文本”应该具有原始价值,并且神秘地直到今天它始终如此,这表明我所拥有的东西是脆弱的,但我做错了什么?

TIA

2 个答案:

答案 0 :(得分:4)

您忘记了流的当前位置。将“x,y,z”数据写入流后,流的位置将指向数据的末尾。您需要移回流的位置以读取数据。像这样:

    static void stuff2(Stream ms)
    {
        ms.Seek(0, SeekOrigin.Begin);
        using (var sr = new StreamReader(ms))
        {
            stuff3(sr.ReadToEnd());
        }

    }

答案 1 :(得分:1)

你必须“重置”你的记忆流。 将您的代码更改为:

[TestMethod]
public void stuff()
{
    using (var ms = new MemoryStream())
    {
        using (var sw = new StreamWriter(ms))
        {
            sw.Write("x,y,z"); //"x,y,z" is usually a line of string data from a textfile
            sw.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            stuff2(ms);
        }
    }

}