简体   繁体   中英

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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