How to truncate a file in c#?

27,175

Solution 1

Try to play around with FileStream.SetLength

FileStream fileStream = new FileStream(...);
fileStream.SetLength(sizeInBytesNotChars);

Solution 2

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.

Solution 3

As opposed to trying to do this yourself, I'd really recommend using something like log4net; it has a lot of this sort of useful functionality built in.

Solution 4

When the file is over 500000 bytes, it will cut the beginning 250000 bytes off from the file so the remaining file is 250000 bytes long.

FileStream fs = new FileStream(strFileName, FileMode.OpenOrCreate);
        if (fs.Length > 500000)
        {
            // Set the length to 250Kb
            Byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, (int)fs.Length);
            fs.Close();
            FileStream fs2 = new FileStream(strFileName, FileMode.Create);
            fs2.Write(bytes, (int)bytes.Length - 250000, 250000);
            fs2.Flush();
        } // end if (fs.Length > 500000) 

Solution 5

By doing this:

if(new FileInfo("<your file path>").Length > 1000000)
{
    File.WriteAllText("<your file path>", "");
}
Share:
27,175
user186246
Author by

user186246

Updated on February 18, 2020

Comments

  • user186246
    user186246 about 4 years

    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

  • irag10
    irag10 almost 12 years
    This reads the whole file into memory. Not ideal if it's really big.