Writing C# debug output to .txt file

戏子无情 提交于 2019-11-27 13:02:43

问题


I'm running code on a microcontroller with .NET Micro Framework, and I want my debug output to write to a text file. How does this work?


回答1:


Use Trace. It is designed to do what you need.

using System;
using System.Diagnostics;

class Test
{
    static void Main()
    {
       Trace.Listeners.Add(new TextWriterTraceListener("yourlog.log"));
       Trace.AutoFlush = true;
       Trace.Indent();
       Trace.WriteLine("Entering Main");
       Console.WriteLine("Hello World.");
       Trace.WriteLine("Exiting Main");
       Trace.Unindent();
       Trace.Flush();
    }
}



回答2:


The most flexible solution for using a out-of-the-box tracing is to make an application configuration file that will define trace listeners.

<configuration>
  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add name="textListener" 
             type="System.Diagnostics.TextWriterTraceListener" 
             initializeData="trace.log" />
        <remove name="Default" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

Then, in your application, whenever you want to log something, just do:

Trace.WriteLine("Hello, this is a trace");

But the power of the TraceListener class lies into its granularity. You can chose between Error, Info and Warning levels and define different log file for whatever level you need to trace. Using configuration files makes it also easier to disable tracing in your application because you don't need to recompile your application.

For more informations on tracing system, check this MSDN article.




回答3:


Ekk is right about Trace being a better design, however that doesn't answer the question, which would be fine in the absence of a direct solution. The OP or someone may have inherited a code base which uses Debug throughout, and Trace may not be desirable at the time.

I found this solution [http://bytes.com/topic/c-sharp/answers/273066-redirect-output-debug-writeline] :

TextWriterTraceListener[] listeners = new TextWriterTraceListener[] {
new TextWriterTraceListener("C:\\debug.txt"),
new TextWriterTraceListener(Console.Out)
};

Debug.Listeners.AddRange(listeners);

Debug.WriteLine("Some Value", "Some Category");
Debug.WriteLine("Some Other Value");



回答4:


You will have to do something like this:

// Set up listener
string filename = @"C:\listener.txt";
FileStream traceLog = new FileStream(filename, FileMode.OpenOrCreate);
TextWriterTraceListener listener = new TextWriterTraceListener(traceLog);

// Output to listener
listener.WriteLine("Trace message here");

// Flush any open output before termination.
// Maybe in an override of Form.OnClosed.
listener.Flush();

Taken from here.

Another related question



来源:https://stackoverflow.com/questions/7926577/writing-c-sharp-debug-output-to-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!