Search code examples
c#directoryexists

How to delete folders created older than last 7 days with C#?


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 ?


Solution

  • 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.