@@ -295,7 +295,7 @@ private static void CreateDailyBackupIfNeeded()
295295 /// specified maximum, are retained.
296296 /// </summary>
297297 /// <remarks>This method removes the oldest backup files first, keeping only the most recent backups as
298- /// determined by file creation time . It is intended to prevent excessive accumulation of backup files and manage
298+ /// determined by the timestamp in the filename . It is intended to prevent excessive accumulation of backup files and manage
299299 /// disk space usage.</remarks>
300300 /// <param name="backupFolderPath">The full path to the directory containing the backup files to be managed. Cannot be null or empty.</param>
301301 /// <param name="settingsFileName">The file name pattern used to identify backup files for cleanup.</param>
@@ -304,7 +304,7 @@ private static void CleanupBackups(string backupFolderPath, string settingsFileN
304304 {
305305 var backupFiles = Directory . GetFiles ( backupFolderPath )
306306 . Where ( f => f . EndsWith ( settingsFileName ) || f . EndsWith ( GetLegacySettingsFileName ( ) ) )
307- . OrderByDescending ( f => File . GetCreationTime ( f ) )
307+ . OrderByDescending ( f => ExtractTimestampFromFilename ( f ) )
308308 . ToList ( ) ;
309309
310310 if ( backupFiles . Count > maxBackupFiles )
@@ -322,6 +322,42 @@ private static void CleanupBackups(string backupFolderPath, string settingsFileN
322322 }
323323 }
324324
325+ /// <summary>
326+ /// Extracts the timestamp from a backup filename.
327+ /// </summary>
328+ /// <remarks>Backup filenames are formatted as yyyyMMddHHmmss_SettingsName.ext. This method extracts
329+ /// the timestamp portion and parses it as a DateTime for ordering purposes. If the timestamp cannot be parsed,
330+ /// DateTime.MinValue is returned.</remarks>
331+ /// <param name="filePath">The full path to the backup file.</param>
332+ /// <returns>The timestamp extracted from the filename, or DateTime.MinValue if parsing fails.</returns>
333+ private static DateTime ExtractTimestampFromFilename ( string filePath )
334+ {
335+ try
336+ {
337+ var fileName = Path . GetFileName ( filePath ) ;
338+
339+ // Extract the timestamp prefix (yyyyMMddHHmmss format, 14 characters)
340+ if ( fileName . Length >= 14 )
341+ {
342+ var timestampString = fileName . Substring ( 0 , 14 ) ;
343+
344+ // Parse the timestamp
345+ if ( DateTime . TryParseExact ( timestampString , "yyyyMMddHHmmss" , null ,
346+ System . Globalization . DateTimeStyles . None , out var timestamp ) )
347+ {
348+ return timestamp ;
349+ }
350+ }
351+ }
352+ catch
353+ {
354+ // If any error occurs, return MinValue to sort this file as oldest
355+ Log . Warn ( $ "Failed to extract timestamp from filename: { filePath } ") ;
356+ }
357+
358+ return DateTime . MinValue ;
359+ }
360+
325361 /// <summary>
326362 /// Creates a backup of the specified settings file in the given backup folder with the provided backup file name.
327363 /// </summary>
0 commit comments