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
The truncate function changes the size of filename to length . If length is shorter than the previous length, data at the end will be lost. The file must be writable by the user to perform this operation. If length is longer, holes will be added to the end.
The truncate() method resizes the file to the given number of bytes. If the size is not specified, the current position will be used.
Try to play around with FileStream.SetLength
FileStream fileStream = new FileStream(...);
fileStream.SetLength(sizeInBytesNotChars);
Close the file and then reopen it using FileMode.Truncate.
Some log implementations archive the old file under an old name before reopening it, to preserve a larger set of data without any file getting too big.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With