If you want still want your output to hit the console, you can use Console.SetOut and give it two destinations at once, one being the main console window and the other being your internal store.
You could write a simple helper class like this:
public class OutputCapture : TextWriter, IDisposable
{
private TextWriter stdOutWriter;
public TextWriter Captured { get; private set; }
public override Encoding Encoding { get { return Encoding.ASCII; } }
public OutputCapture()
{
this.stdOutWriter = Console.Out;
Console.SetOut(this);
Captured = new StringWriter();
}
override public void Write(string output)
{
// Capture the output and also send it to StdOut
Captured.Write(output);
stdOutWriter.Write(output);
}
override public void WriteLine(string output)
{
// Capture the output and also send it to StdOut
Captured.WriteLine(output);
stdOutWriter.WriteLine(output);
}
}
Then in your main code you could wrap your statements as shown below:
void Main()
{
// Wrap your code in this using statement...
using (var outputCapture = new OutputCapture())
{
Console.Write("test");
Console.Write(".");
Console.WriteLine("..");
Console.Write("Second line");
// Now you can look in this exact copy of what you've been outputting.
var stuff = outputCapture.Captured.ToString();
}
}
You could change this to have multiple destinations, so you could create an internal store that was something like List<string>
instead if you wanted to.
Background: I did something along these lines (although I didn't keep a copy of the output) when I wanted to get my NHibernate queries to be output into the SQL Output tab in LINQPad. I wrote about it here (there's a Github repo and NuGet packages too): https://tomssl.com/2015/06/30/see-your-sql-queries-when-using-nhibernate-with-linqpad/