StringStream in C#

AndreyAkinshin picture AndreyAkinshin · Nov 15, 2011 · Viewed 113k times · Source

I want to be able to build a string from a class that I create that derives from Stream. Specifically, I want to be able to write code like this:

void Print(Stream stream) {
    // Some code that operates on a Stream.
}

void Main() {
    StringStream stream = new StringStream();
    Print(stream);
    string myString = stream.GetResult();
}

Can I create a class called StringStream that makes this possible? Or is such a class already available?

Update: In my example, the method Print is provided in a third-party external DLL. As you can see, the argument that Print expects is a Stream. After printing to the Stream, I want to be able to retrieve its content as a string.

Answer

Lu55 picture Lu55 · Apr 24, 2013

You can use tandem of MemoryStream and StreamReader classes:

void Main()
{
    string myString;

    using (var stream = new MemoryStream())
    {
        Print(stream);

        stream.Position = 0;
        using (var reader = new StreamReader(stream))
        {
            myString = reader.ReadToEnd();
        }
    }
}