C# - Delete files from a folder those are older than some number of days by using C Sharp

Scenario: Download Script

You are working as C# developer and you need to write a program that should delete the files from a folder older than some number of days.


Solution:

You can write Console Application for this purpose.  Below is the script that can be used to delete older files, You can change folder path according to your folder path and number of days you like to pass for old files. I only added System.IO namespace.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace _02_DeleteOldFilesFromFolder
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declare Variables and Set Values
            string FileDirectory;
            int RetentionPeriodinDays;

            FileDirectory = "C:\\Source\\";
            RetentionPeriodinDays = 2;

            var files = new DirectoryInfo(FileDirectory).GetFiles("*.*");
            foreach (var file in files)
            {
                
                if (file.CreationTime < DateTime.Today.AddDays(-RetentionPeriodinDays))
                {
                    file.Delete();
                }
            }

        }
    }
}