Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a file in c#?

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

like image 374
user186246 Avatar asked Jun 30 '11 16:06

user186246


People also ask

What does truncating a file mean in C?

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.

What is the use of truncate () method in file?

The truncate() method resizes the file to the given number of bytes. If the size is not specified, the current position will be used.


2 Answers

Try to play around with FileStream.SetLength

FileStream fileStream = new FileStream(...);
fileStream.SetLength(sizeInBytesNotChars);
like image 99
sll Avatar answered Oct 21 '22 04:10

sll


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.

like image 43
Steve Townsend Avatar answered Oct 21 '22 03:10

Steve Townsend