Check File Creation Date and Delete

Asked

Viewed 2,717 times

1

I created a Backup application, it saves the files in zip format DD-MM-YYY - 00-00-00.zip, but would like to know how I would do to check creation date for deletion, because the name of the files are distinguished by saving up to the seconds.

Should I check the file directory? Code to identify the farm:

DateTime data = Directory.GetCreationTime(diretorio);

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

1 answer

3


I found some answers that might help you.

Steve Danner’s response in the 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 response to 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 the OS:

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;
    }
}

Has more some here.

I put in the Github for future reference.

  • Thanks for the reply and the mustache fix.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.