AndreyAkinshin AndreyAkinshin - 1 month ago 23
C# Question

StringStream in C#

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 Source

You can use a StringWriter to write values to a string. It provides a stream-like syntax (though does not derive from Stream) which works with an underlying StringBuilder.