How to truncate a file in c#?

Viewed 28469

I am writing actions done by the program in C# into a file by using Trace.Writeln() function. But the file is becoming too large. How to truncate this file when it grows to 1MB?

TextWriterTraceListener traceListener = new TextWriterTraceListener(File.AppendText("audit.txt"));
Trace.Listeners.Add(traceListener);
Trace.AutoFlush = true;

What should be added to the above block

8 Answers

Late answer, but you might try:

StreamWriter sw = new StreamWriter(YourFileName, false);
sw.Write("");
sw.Flush();
sw.Close();

Sending false as the second param of StreamWriter() tells it NOT to append, resulting in it overwriting the file. In this case with an empty string, effectively truncating it.

Related