1. // Keep track of the original output writer
  2. TextWriter originalOut = Console.Out;
  3.  
  4. // Override console output with a custom one
  5. StringWriter buf = new StringWriter();
  6. Console.SetOut(buf);
  7.  
  8. Console.WriteLine("This will be captured!");
  9.  
  10. // Capture output!
  11. buf.Flush();
  12. string capturedOutput = buf.ToString();
  13.  
  14. // Restore original output writer
  15. Console.SetOut(originalOut);