[Solved]-Delete Files older than X Months,Days,Minute in a Directory- C# .NET


In this post, I will explain how to delete files in a directory that are older than a specified duration, such as days, months, years, minutes, or seconds. Specifically, I will focus on deleting files older than a certain number of months, days, or years.

I'm currently working on a project where I need to delete files older than 60 days. In other words, I want to keep files created within the last 60 days and delete all others.

To accomplish this task, we can utilize the following code. I've created a simple console application and provided the necessary C# code for you.

You can delete files using the properties of the `FileSystemInfo` class. The `CreationTime` or `LastWriteTime` properties of the file can be used for this purpose.

If you prefer to delete files based on their last modification date, you can utilize the `LastWriteTime` property of the `FileSystemInfo` class.

You can access the last modification date of the file using the `LastWriteTime` property of the `FileSystemInfo` class.

In this post, we are going to cover the following points:

  • Deleting files from a folder using the last modified property in C#
  • Deleting old files in a folder in C#
  • Removing files that are older than a specified number of days

While working on a C# Windows program, I encountered a scenario where I needed to check the creation time of a file and delete it if it was older than 7 days. My Windows app runs constantly, generating numerous files, and a separate thread is responsible for checking that the files are not older than 7 days. To achieve this, I've written the above code to remove files older than 7 days, and it's functioning correctly.

If you have any queries or doubts, please feel free to comment.

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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            DeleteOlderFile(60);
        }

        public static void DeleteOlderFile(int numberdays)
        {
            try
            {
                //get all files from folder
                string dirName = System.Web.HttpContext.Current.Server.MapPath("/DownloadedContent");
                string[] files = Directory.GetFiles(dirName);
                foreach (string file in files)
                {
                    FileInfo fi = new FileInfo(file);
                    if (fi.CreationTime < DateTime.Now.AddMinutes(-numberdays))
                        fi.Delete();
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}


  • string dirName = System.Web.HttpContext.Current.Server.MapPath("/DownloadedContent");: This line retrieves the physical path of the folder named "DownloadedContent" within the web application. It uses Server.MapPath method to map the virtual path to the physical path.
  • string[] files = Directory.GetFiles(dirName);: This line retrieves an array of strings representing the file paths of all files within the specified directory (DownloadedContent).
  • foreach (string file in files) { ... }: This loop iterates over each file path in the files array.
  • FileInfo fi = new FileInfo(file);: This line creates a FileInfo object (fi) for each file path obtained from the loop. It allows accessing file attributes and methods.
  • if (fi.CreationTime < DateTime.Now.AddMinutes(-numberdays)) fi.Delete();: This conditional statement checks if the creation time of the file (fi.CreationTime) is older than the specified number of days (DateTime.Now.AddMinutes(-numberdays)). If the condition is true, the file is deleted using the Delete() method of the FileInfo object (fi).

This function iterates through all files in the specified folder, checks if each file is older than the specified number of days, and deletes it if it meets the criteria. 

You can also use 1 line Lamba Query:

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

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            DeleteOlderFileUsingLamda(60);
        }

        public static void DeleteOlderFileUsingLamda(int numberdays)
        {
            try
            {
                //get all files from folder
                string dirName = System.Web.HttpContext.Current.Server.MapPath("/DownloadedContent");
                Directory.GetFiles(dirName)
                         .Select(f => new FileInfo(f))
                         .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-numberdays))
                         .ToList()
                         .ForEach(f => f.Delete());
            }
            catch (Exception ex)
            {

            }
        }
    }
}

The provided code snippet is a C# example that demonstrates how to delete files from a specific folder if they haven't been accessed for a certain number of months. The code is designed to be used in a web application context, as it utilizes System.Web.HttpContext to determine the path of the directory. 

Directory Path:

string dirName = System.Web.HttpContext.Current.Server.MapPath("/DownloadedContent");

This line defines the directory path from which files will be selected. Server.MapPath translates a virtual path (in this case, "/DownloadedContent") into a physical path on the server. This is useful in web applications where the physical path may not be directly known or may change depending on the environment (e.g., development, staging, production).

Get Files:

Directory.GetFiles(dirName)

This part retrieves all the file paths in the specified directory (dirName).

File Information:

.Select(f => new FileInfo(f))

Each file path is converted into a FileInfo object. This conversion is necessary because FileInfo provides access to properties such as LastAccessTime, which is needed to determine when the file was last accessed.

Filter Files:

.Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-numberdays))

This line filters the files by their last access time. It selects only those files that were last accessed before a certain threshold. The DateTime.Now.AddMonths(-numberdays) expression calculates the date before the current date by the number of months specified by numberdays. The name numberdays is a bit misleading in this context since the operation involves months; a more appropriate name might be numberOfMonths or similar to reflect the actual operation being performed.

Delete Files:

.ToList().ForEach(f => f.Delete());

The filtered list of files is converted to a list with .ToList(), and then .ForEach(f => f.Delete()) iterates over each FileInfo object and deletes the corresponding file from the filesystem.