Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect .NET StreamWriter output to a String variable

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

like image 811
Eric Avatar asked Oct 24 '08 20:10

Eric


3 Answers

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'
like image 170
Ely Avatar answered Oct 14 '22 17:10

Ely


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?

like image 34
Matt Ellis Avatar answered Oct 14 '22 19:10

Matt Ellis


You should be able to do what you need using a Memory Stream.

MemoryStream mem = new MemoryStream(); 
StreamWriter sw = new StreamWriter(mem);
sw.WriteLine("Foo"); 
// then later you should be able to get your string.
// this is in c# but I am certain you can do something of the sort in C++
String result = System.Text.Encoding.UTF8.GetString(mem.ToArray(), 0, (int) mem.Length);
like image 12
Pascal Ganaye Avatar answered Oct 14 '22 19:10

Pascal Ganaye