Redirecting tracing to a file


The code snippet shows how to write the output of trace object to a file.

The code snippet shows how to write the output of trace object to a file.


Namespaces to be used


using System.Diagnostics;


c# code to write trace to file


Trace.Listeners.Clear();
FileStream fs = new FileStream(@"c:\mylog.log", FileMode.Create, FileAccess.Write);
Trace.Listeners.Add(new TextWriterTraceListener (fs));
Trace.WriteLine("any data to be added to log file");
Trace.Flush();


Explanation:

Clear all the listeners.
Create a file with write mode
To the trace listeners add the object of TextWriterTraceListener based on FileStream Object
The data is first written to the buffer so in order to save to file use flush().


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: