[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make a log file with multiple overflow versions in C#

example

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.