Debug.Writeline

2019-08-28 21:20发布

问题:

I am trying to write some messages to a text file using Debug.WriteLine("Message").

Here is the code.

Dim Tr As TextWriterTraceListener
Tr = New TextWriterTraceListener(System.IO.File.CreateText("Output1.txt"))
'Tr = New TextWriterTraceListener(System.Console.Out)
Debug.Listeners.Add(Tr)
Debug.WriteLine("Test Message")

I see the output1.txt file being created, but nothing is being written in the file.

How can I fix this problem?

回答1:

The TextWriterTraceListener buffers data and only writes it when the buffer is full, it is closed/disposed, or Flush() is called:

Dim Tr As TextWriterTraceListener
Tr = New TextWriterTraceListener(System.IO.File.CreateText("Output1.txt"))
'Tr = New TextWriterTraceListener(System.Console.Out)
Debug.Listeners.Add(Tr)
Debug.WriteLine("Test Message")
Tr.Flush()


回答2:

You need to flush the buffer of the TextWriterTraceListener.

After writing to the trace listener you need to:

Tr.Flush();

See the documentation for Flush on MSDN.



回答3:

You have to close and dispose the TextWriterTraceListener

Tr.Close()
Tr.Dispose()