Home > Software engineering >  How to delete folders created older than last 7 days with C#?
How to delete folders created older than last 7 days with C#?

Time:09-19

The folder structure is Year/Month/Day. For example, in 'C:\folder\2022\09' there are folders named 1 to 30 (because there are 30 days in august). Likewise, in the next days, a folder will be created every day, and its name will only be the number of that day, for example 'C:\folder\2022\09\19' for the file created today. When the 'sample.exe' that I want to create with c# is run, it will delete the folders created older than the last 7 days and will not touch the folders created in the last 7 days. How can I do that ?

CodePudding user response:

I think this is about it.

int limit = 7;

foreach (string dir in Directory.GetDirectories(yourPath))
{
   DateTime createdTime = new DirectoryInfo(dir).CreationTime;
   if (createdTime < DateTime.Now.AddDays(-limit))
   {
       Directory.Delete(dir);
    }
 }

CodePudding user response:

This answer assumes you are measuring the date based on the name of the folder and it's parents, not the metadata of the folder(s).

Gather a list of all the possible folders to delete, and get the full paths.

string directoryPath = @"C:\folder\2022\09\19";

If you're lazy and only intend on this being ran on Windows, split by backslash.

string[] pathSegments = directoryPath.Split('\\');

The last element represents the day. The second to last represents the month, and the third to last represents the year. You can then construct your own DateTime object with that information.

DateTime pathDate = new DateTime(
    year: int.Parse(pathSegments[^3]),
    month: int.Parse(pathSegments[^2]),
    day: int.Parse(pathSegments[^1])
);

You can now easily compare this DateTime against DateTime.Now or any other instance.

CodePudding user response:

Just get the folder name with Directories.GetDirectories(yourPath) then parse the folder names. You can use string[] date = String.Split('\\') and then

int year = date[0];
int month = date[1];
int day = date[2];
DateTime folderDate = new DateTime(year, month, day);

Then you can just check if that date is 7 days behind DateTime.Now and delete the necessary folders using Directory.Delete(folderPath);

  • Related