Redirect.NET StreamWriter salida a una variable de cadena


Me gustaría saber si es posible redirigir la salida de StreamWriter a una variable

Algo como

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

Entonces myString contendrá Foo. La razón por la que me gustaría hacer esto es reutilizar una función compleja. Probablemente debería refactorizarlo en una función de retorno de cadena, pero aún así sería un buen truco saber

Author: leppie, 2008-10-25

5 answers

StreamWriter y StringWriter ambos extienden TextWriter, tal vez podría refactorizar su método que utiliza StreamWriter para usar TextWriter en su lugar para que pueda escribir en una secuencia o una cadena?

 22
Author: Matt Ellis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 20:40:17

Puede hacer esto con un StringWriter escribiendo el valor directamente en un objeto constructor de cadenas

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
// now, the StringWriter instance 'sw' will write to 'sb'
 37
Author: Ely,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 20:46:19

Pruebe este código =]

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string s = sb.ToString(); <-- Now it will be a string.
 5
Author: CloudyMarble,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-15 03:56:47

Debería ser capaz de hacer lo que necesita usando un flujo de memoria.

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);
 5
Author: Pascal Ganaye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-06 06:19:32

Refactoriza el método para devolver la cadena como mencionaste que podrías. Piratearlo de la manera en que lo intentas, aunque académicamente interesante, enturbiará el código y hará que sea muy difícil de mantener para cualquiera que te siga.

 0
Author: Rob Prouse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 20:41:49