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().