static void BackupLogFile(FileReference LogFile, TimeSpan RetentionSpan) { string LogPrefix = LogFile.GetFileNameWithoutExtension() + "-backup-"; string LogSuffix = LogFile.GetExtension(); if (FileReference.Exists(LogFile)) { string Timestamp = FileReference.GetLastWriteTime(LogFile).ToString("yyyy.MM.dd-HH.mm.ss"); string UniqueSuffix = ""; for (int NextSuffixIdx = 2; ; NextSuffixIdx++) { FileReference BackupLogFile = FileReference.Combine(LogFile.Directory, String.Format("{0}{1}{2}{3}", LogPrefix, Timestamp, UniqueSuffix, LogSuffix)); if (!FileReference.Exists(BackupLogFile)) { try { FileReference.Move(LogFile, BackupLogFile); } catch (Exception Ex) { Log.TraceWarning("Unable to backup {0} to {1} ({2})", LogFile, BackupLogFile, Ex.Message); Log.TraceLog(ExceptionUtils.FormatException(Ex)); } break; } UniqueSuffix = String.Format("_{0}", NextSuffixIdx); } } DateTime DeleteTime = DateTime.UtcNow - RetentionSpan; foreach (FileInfo File in new DirectoryInfo(LogFile.Directory.FullName).EnumerateFiles(LogPrefix + "*" + LogSuffix)) { if (File.LastWriteTimeUtc < DeleteTime) { File.Delete(); } } }