Make a log file with multiple overflow versions in C#


This program makes a log file named log.txt. When you write entries into it, the program checks the file’s size. If the size exceeds 100 bytes (you would make this larger for a real application), the program renames the file log.txt.1 and starts a new log.txt file. It bumps down older versions of the log to log.txt.2, and log.txt.3. This version uses 3 backup versions and discards older files, but you can also change that in a real application.

The following WriteToLog method does all of the work.

// If the file exceeds max_size bytes, move it to a new file
// with .1 appended to the name and bump down older versions.
// (E.g. log.txt.1, log.txt.2, etc.)
// Then write the text into the main log file. 
private void WriteToLog(string new_text, string file_name,
    long max_size, int num_backups)
    // See if the file is too big.
    FileInfo file_info = new FileInfo(file_name);
    if (file_info.Exists && file_info.Length > max_size)
        // Remove the oldest version if it exists.
        if (File.Exists(file_name + "." + num_backups.ToString()))
            File.Delete(file_name + "." + num_backups.ToString());

        // Bump down earlier backups.
        for (int i = num_backups - 1; i > 0; i--)
            if (File.Exists(file_name + "." + i.ToString()))
                // Move file i to file i + 1.
                File.Move(file_name + "." + i.ToString(),
                     file_name + "." + (i + 1).ToString());

        // Move the main log file.
        File.Move(file_name, file_name + ".1");

    // Write the text.
    File.AppendAllText(file_name, new_text + '\n');

The code first checks whether the file exists and whether its size exceeds the maximum allowed size. If so, it moves the logs around.

First the code deletes the oldest allowed backup log if it exists. It then bumps backup logs down so, for example, log.txt.2 becomes log.txt.3. It then moves the “live” log to log.txt.1.

The method finishes by appending the new text to the “live” log file. Note that File.AppendAllText automatically creates the file if it doesn’t already exist.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in files and tagged , , , , , , , . Bookmark the permalink.

One Response to Make a log file with multiple overflow versions in C#

  1. Pingback: Use the File.Replace method to backup files in C# -

Leave a Reply

Your email address will not be published. Required fields are marked *