views:

1994

answers:

3

I'd like to know if it is possible to redirect StreamWriter output to a variable

Something like

String^ myString;
StreamWriter sw = gcnew StreamWriter([somehow specify myString])
sw->WriteLine("Foo");

then myString will contain Foo. The reason I would like to do this is to reuse a complex function. I should probably refactor it into a String returning function but it still would be a nice hack to know

+7  A: 

StreamWriter and StringWriter both extend TextWriter, perhaps you could refactor your method that uses StreamWriter to use TextWriter instead so it could write to either a stream or a string?

Matt Ellis
You beat me by just seconds!
Matt Ellis
A: 

Refactor the method to return string as you mentioned you could. Hacking it the way you are attempting, while academically interesting, will muddy the code and make it very hard to maintain for anyone that follows you.

Rob Prouse
+6  A: 

You can do this with a StringWriter writing the value directly to a string builder object

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
// now, the StringWriter instance 'sw' will write to 'sb'
Ely