Check file creation date and delete

1

I created a Backup application, it saves zipped files in DD-MM-YYY - 00-00-00.zip format, but I would like to know how I would do the create date check for deletion, because the files' names are different for saving to the seconds.

Should I check the files directory? Creation ID code:

DateTime data = Directory.GetCreationTime(diretorio);

The operation should be, if the creation date is more than 10 days for example delete it.

    
asked by anonymous 04.11.2014 / 14:00

1 answer

3

I found some answers that might help you.

Steve Danner's Response to OS :

using System.IO; 

string[] files = Directory.GetFiles(dirName);

foreach (string file in files) {
   FileInfo fi = new FileInfo(file);
   if (fi.LastAccessTime < DateTime.Now.AddMonths(-3))
      fi.Delete();
}

Uri Abramson's answer in the OS :

Directory.GetFiles(dirName)
     .Select(f => new FileInfo(f))
     .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
     .ToList()
     .ForEach(f => f.Delete());

More complete answer from Adriano Repetti in SO :

static class Helpers {
    public static void DeleteOldFiles(string folderPath, uint maximumAgeInDays, params string[] filesToExclude) {
        DateTime minimumDate = DateTime.Now.AddDays(-maximumAgeInDays);
        foreach (var path in Directory.EnumerateFiles(folderPath)) {
            if (IsExcluded(path, filesToExclude))
                continue;

            DeleteFileIfOlderThan(path, minimumDate);
        }
    }

    private const int RetriesOnError = 3;
    private const int DelayOnRetry = 1000;

    private static bool IsExcluded(string item, string[] exclusions) {
        foreach (string exclusion in exclusions) {
            if (item.Equals(exclusion, StringComparison.CurrentCultureIgnoreCase))
                return true;
        }

        return false;
    }

    private static bool DeleteFileIfOlderThan(string path, DateTime date) {
        for (int i = 0; i < RetriesOnError; ++i) {
            try {
                FileInfo file = new FileInfo(path);
                if (file.CreationTime < date)
                    file.Delete();

                return true;
            } catch (IOException) {
                System.Threading.Thread.Sleep(DelayOnRetry);
            } catch (UnauthorizedAccessException) {
                System.Threading.Thread.Sleep(DelayOnRetry);
            }
        }

        return false;
    }
}

There are more some here .

I placed GitHub for future reference .

    
04.11.2014 / 14:18