Tuesday, July 15, 2008

How to capture the output from Console.WriteLine

Sometimes, windows/console application needs to capture the output from console.writeline for debugging purpose. It's useful if the application can run in verbose mode, so that we can know at which point the system crashes. Maybe you might think we can implement ConsoleTraceListener Class in .Net 2.0.

While doing some tutorials on Linq on .Net 3.0, I found the sample have another simpler way to achieve that. Here are the steps:

1) Create a windows application


2) Design a simple GUI. Button represents you business logic and multiline textbox means the trace information.


3) Set the StreamWriter to the Console output, re-capture it with TextWriter will do.

Imports System.IO

Public Class Form1
Private ReadOnly _OutputStreamWriter As StreamWriter = New StreamWriter(New MemoryStream())

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Capture console output
Dim writer As StreamWriter = _OutputStreamWriter
Dim oldConsoleOut As TextWriter = Console.Out
Console.SetOut(writer)
Dim stream As MemoryStream = CType(writer.BaseStream, MemoryStream)
stream.SetLength(0)

DoSomething
' set to result pane
writer.Flush()
Console.SetOut(oldConsoleOut)
TextBox1.Text += writer.Encoding.GetString(stream.ToArray())

End Sub

Private Sub DoSomething()
Console.WriteLine("Hello world!")
End Sub
End Class

4) Here's the final result:

5 comments:

俊锋 said...
This comment has been removed by the author.
jeff said...

Thank you for your brilliant work on "capture Console output", This helps me a lot.

ThatSkinnyGuy said...

With all of the complicated stuff out there on the interwebs to do this exact same thing, I'm surprised at how simple it can really be.
I'm trying to show the payloads of multicast packets in a textbox. This really really helped out.
It's as complicated as it needs to be and no more.
Thank You.

gary said...

jeff & ThatSkinnyGuy: hope it helps :)

Blogger said...

Are you trying to make money from your websites via popunder advertisments?
In case you are, have you tried using PropellerAds?