[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use Debug and Trace listeners in C#

[Use Debug and Trace listeners in C#]

By default, the Debug and Trace classes send messages to the Console window. Sometimes it might be nice to capture that text and save it in a file. This example shows how you can do that.

The Debug and Trace classes have a shared Listeners collection that contains listener objects. The classes actually send their message to those objects rather than directly to the Console window. Initially the Listeners collection contains a single listener that sends the text it receives to the Console window.

You can remove the default listener from the collection if you like, and you can add new listeners to the collection. This example uses the following code to add a TextWriterListener object that appends the text it receives to a text file.

// Make the listener. private void Form1_Load(object sender, EventArgs e) { string trace_file = Application.StartupPath + "//trace.txt"; Trace.Listeners.Add(new TextWriterTraceListener(trace_file)); Trace.AutoFlush = true; }

The code composes a file name. It then creates a TextWriterTraceListener object, passing its constructor the file name, and adds the new listener to the Trace object's Listeners collection. The Debug and Trace classes share the Listeners collection so this listener will write both Trace and Debug messages into the file.

By default, the Debug and Trace classes do not flush their text buffers into text files, so if the program ends without you explicitly flushing the output, some or all of the text may not be written into the file. The program avoids this problem by setting the Trace class's AutoFlush property to true.

If you enter a message in the program's TextBox and click Debug, the program executes the following code.

// Send a message to the Debug listeners. private void btnDebug_Click(object sender, EventArgs e) { Debug.WriteLine(txtMessage.Text); txtMessage.Clear(); txtMessage.Focus(); }

This code uses the Debug.WriteLine method to send a message to the listeners. The default listener sends the text to the Console window and the other listener appends the text to the text file trace.txt.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.