haughtonomous
haughtonomous

Reputation: 4850

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

Upvotes: 1

Views: 553

Answers (2)

Piotr Stapp
Piotr Stapp

Reputation: 19830

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

}

Upvotes: 1

Scott
Scott

Reputation: 1876

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

    }

Upvotes: 4

Related Questions