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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/235156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:25:29  来源:igfitidea点击:

Redirect .NET StreamWriter output to a String variable

.netstreamwriter

提问by Eric

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. 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

那么 myString 将包含 Foo。我想这样做的原因是重用一个复杂的函数。我可能应该将它重构为一个 String 返回函数,但它仍然是一个很好的了解

采纳答案by Matt Ellis

StreamWriterand StringWriterboth 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?

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

回答by Ely

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'

回答by Matt Ellis

Try out this code =]

试试这个代码 =]

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

回答by Pascal Ganaye

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);

回答by Rob Prouse

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.

正如您提到的那样,重构方法以返回字符串。以您尝试的方式对其进行破解,虽然在学术上很有趣,但会使代码变得混乱,并使跟随您的任何人都很难维护。