Redirect Console.WriteLine() output to string

ⅰ亾dé卋堺 提交于 2019-12-10 23:35:13

问题


I need to take Console.WriteLine() output, and append to a string. I cannot change the Main method to simply append to a string instead of writing to console - I need a method to read all written lines from the console and append them to a string.

Currently, I have been using a FileStream and redirecting console output into a text file, and then reading from that.

var fs = new FileStream("dataOut.txt", FileMode.Create);
var sw = new StreamWriter(fs);
Console.SetOut(sw);
Console.SetError(sw);

And then Console.WriteLine("whatever") writes to the text file. However, I would like to do this without going back and forth from a text file.

Is something like this possible? I realize that the example below does not.

string outString = "";
Console.SetOut(outString);
Console.SetError(outString);

回答1:


Use a StringWriter:

var sw = new StringWriter();
Console.SetOut(sw);
Console.SetError(sw);
string result = sw.ToString();


来源:https://stackoverflow.com/questions/38854581/redirect-console-writeline-output-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!