简体   繁体   English

将.NET StreamWriter输出重定向到String变量

[英]Redirect .NET StreamWriter output to a String variable

I'd like to know if it is possible to redirect StreamWriter output to a variable 我想知道是否可以将StreamWriter输出重定向到变量

Something like 就像是

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

then myString will contain Foo. 那么myString将包含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 我应该将它重构为一个String返回函数,但它仍然是一个很好的黑客知道

You can do this with a StringWriter writing the value directly to a string builder object 您可以使用StringWriter将值直接写入字符串构建器对象

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

StreamWriterStringWriter都扩展了TextWriter,也许你可以重构使用StreamWriter来使用TextWriter的方法,以便它可以写入流或字符串?

Try out this code =] 试试这段代码=]

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string s = sb.ToString(); <-- Now it will be a string.

You should be able to do what you need using a Memory Stream. 您应该能够使用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);

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. 以你学习的方式攻击它,虽然在学术上很有趣,但会使代码变得混乱,并且对于跟随你的人来说很难维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM