简体   繁体   English

MemoryStream之谜

[英]MemoryStream mystery

I have some code that has stopped working. 我有一些已停止工作的代码。 It hasn't itself changed, but it has stopped working. 它本身并没有改变,但是已经停止工作。

It concerns using a memorystream to import some text data from outside an app and pass it around the app, eventually converting the text to a string. 它涉及到使用内存流从应用程序外部导入一些文本数据并将其传递给应用程序,最终将文本转换为字符串。 The following code fragment encapsulates the problem: 以下代码片段封装了该问题:

    [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.
    }

Am I missing something? 我想念什么吗? 'text' should have the original value, and mystifyingly until today it always did, which suggests that what I have odne is fragile, but what am I doing wrong? “文本”应该具有原始价值,并且直到今天一直神秘地一直存在,这表明我的特长是脆弱的,但是我在做什么错呢?

TIA TIA

You are forgetting about the current position of the stream. 您忘记了流的当前位置。 After you write the "x,y,z" data to the stream, the stream's position will be pointing at the end of the data. 将“ x,y,z”数据写入流后,流的位置将指向数据的末尾。 You need to move back the position of the stream to read out the data. 您需要移回流的位置以读出数据。 Like so: 像这样:

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

    }

You have to "reset" your mememory stream. 您必须“重置”您的内存流。 Change your code to: 将您的代码更改为:

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

}

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

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