3

I'm running code and I want my debug output to write to a text file. How does this work?

I tried to write:

TextWriterTraceListener[] listeners = new TextWriterTraceListener[] {
            new TextWriterTraceListener("W:\\C.txt"),
            new TextWriterTraceListener(Console.Out)};
Debug.Listeners.AddRange(listeners);
Debug.WriteLine("Some Value", "Some Category");

But it still writes to the output window...

What should I do?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tehila
  • 73
  • 1
  • 7
  • You want to a file and *not* to the console? Take out `new TextWriterTraceListener(Console.Out)`...? – crashmstr Nov 25 '13 at 13:25
  • You are right...what should choose instead of (Console.out) in order to write to text file? – Tehila Nov 26 '13 at 08:40
  • The thing is, it looks like you have *both* in your example: console and text file. Like I said, *don't* specify `Console.Out`, because you will get both. Either remove that *one* line from your array, or just add only a `new TextWriterTraceListener(...)` to `Debug.Listeners`. – crashmstr Nov 26 '13 at 12:39

2 Answers2

7

I found answer on Stack Overflow look at: Writing C# debug output to .txt file

  1. Add listener to Trace
  2. Use trace.

In your case you didn't call Flush for putting record to file.

TextWriterTraceListener[] listeners = new TextWriterTraceListener[] {
            new TextWriterTraceListener("W:\\C.txt"),
            new TextWriterTraceListener(Console.Out)};
Debug.Listeners.AddRange(listeners);
Debug.WriteLine("Some Value", "Some Category");
Debug.Flush()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
4

Use Trace.WriteLine("text"). It's designed exactly for what you are trying to achieve.

Michal B.
  • 5,676
  • 6
  • 42
  • 70