Delete files older than a date

后端 未结 3 484
我寻月下人不归
我寻月下人不归 2020-12-20 20:09

I am currently working on a c# program where I check the creation time of a file and delete it if the file is older than 2 days. I have the following code snippet that shoul

相关标签:
3条回答
  • 2020-12-20 20:49

    You forced to consider only the date part of the creation time-stamp then condition is satisfied and file will be deleted (earlier) anyway I suggest a few modifications to that code:

    static class Helpers {
        public static void DeleteOldFiles(string folderPath, uint maximumAgeInDays,
                                          params string[] filesToExclude) {
            DateTime minimumDate = DateTime.Now.AddDays(-maximumAgeInDays);
    
            var filesToDelete = Directory.EnumerateFiles(folderPath)
                .Where(x => !IsExcluded(x, filesToExclude));
    
            foreach (var eligibleFileToDelete in filesToDelete)
                DeleteFileIfOlderThan(eligibleFileToDelete, minimumDate);
        }
    
        private const int RetriesOnError = 3;
        private const int DelayOnRetry = 1000;
    
        private static bool IsExcluded(string item, string[] exclusions) {
            return exclusions.Contains(item, StringComparer.CurrentCultureIgnoreCase);
        }
    
        private static void DeleteFileIfOlderThan(string path, DateTime date)
        {
            for (int i = 0; i < RetriesOnError; ++i) {
                try {
                    var file = new FileInfo(path);
                    if (file.CreationTime < date)
                        file.Delete();
                }
                catch (IOException) {
                    System.Threading.Thread.Sleep(DelayOnRetry);
                }
                catch (UnauthorizedAccessException) {
                    System.Threading.Thread.Sleep(DelayOnRetry);
                }
            }
        }
    }
    

    Notes

    • I'm still using DateTime.Now, I guess for this kind of operations you do not need any precision measurement (and you're talking about days so your thread may have a scheduled time of hours).
    • If your application uses multiple log files you can specify them all as parameters and they'll be ignored.
    • If you call DeleteOldFiles with 0 for maximumAgeInDays then you'll delay all log files not in use (as specified in the exclusion list).
    • Sometimes files can be in use (even if this should happen seldom in your case). The DeleteFileIfOlderThan function will retry to delete them after a short delay (it mimics Explorer.exe behavior).

    You can call this function in this way:

    Helpers.DeleteOldFiles(@"c:\mypath\", logAge, currentLog);
    

    Few more notes:

    • This code doesn't combine path and file name but if you have to do it you should use Path.Combine(), I guess you do not want to reinvent the wheel each time to check if a path ends with a trailing backslash or not.
    • I/O operations can fail! Always check for exceptions.
    0 讨论(0)
  • 2020-12-20 20:50

    file.Delete does make more sense than File.Delete(path) and Path.Combine() makes a lot more sense than using string.Format.

    I've stumbled across this answer, don't know why I didn't find it before hand after spending ages on google, but this appears to have fixed the problem. DateTime.Compare how to check if a date is less than 30 days old?. The other problem was that I was using the file creation time but for my scenario it made more sense to use lastWriteTime.date.

    0 讨论(0)
  • 2020-12-20 20:57

    I guess an additional problem must be in

    File.Delete(string.Format("{0}/{1}", directory, file));
    

    Your file is of type FileSystemInfo. Maybe you wanted to use file.Name. Example: let's say directory is "c:\" and file points to "c:\myfile.log", your code will try to delete "c:/c:\myfile.log". It's hard for me to guess what exactly you have in these variables.

    Correct replacement is suggested by @HenkHolterman:

    file.Delete();
    
    0 讨论(0)
提交回复
热议问题