Delete Old Files in a Folder in C# – Asp.Net DateTime.AddDays() Method - Delete Files Older Than One Day

← PrevNext →

A few months back I have designed an Online Image optimizer tool, and named it Image Resizer. It’s a free online tool. You can crop and resize an image instantly. What started as an experiment, has now gained some popularity among online users and it’s now serving more than 500 users every day, processing 1000+ pictures at an average, and this figure is steadily rising.

Did I said, Serving 500 users every day. Yes, that’s right. Now, It's not a figure that should make me jump off my seat. However, there was a small issue, which demanded some immediate attention and action.

The issue was, once the images are processed, users download a copy of their processed image, leaving the original copies on the server. Since, the space provided to me on the server is very limited, I have to delete the unwanted files from the folder.

Here, in this post I’ll show you how to keep the latest/current files and delete older files in a folder using Asp.Net. In my case, the files were images. You can remove any type of files using the below codes.

Delete Files That Were Created One Day Before the Current Date

Let me assume, you have created few files today and before and you wish to delete files that you created either yesterday or days before yesterday, without touching today’s files.

Code Behind (C#)
using System;
using System.IO;

public partial class SiteMaster : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] files = Directory.GetFiles(Server.MapPath("~/images/"));
        int iCnt = 0;

        foreach (string file in files)
        {
            divList.InnerHtml = "Found: " + files.Length + " files.";

            FileInfo info = new FileInfo(file);

            info.Refresh();

            if (info.LastWriteTime <= DateTime.Now.AddDays(-1))
            {
                info.Delete();
                iCnt += 1;
            }

            divList.InnerHtml = divList.InnerHtml + "<br > " + iCnt + " files deleted.";
        }
    }
}

You need to focus on two important piece of code. The first is the property called LastWriteTime and the other is the method “AddDays()” of DateTime structure.

After fetching the files from the folder, the code checks each file and its properties. The FileInfo class provides vital information of the files in the folders. Using the property LastWriteTime, I would know when the file was last written to or updated.

Now, we need to find if its old enough to delete the files. To check this I’ll ill use Asp.Net AddDays() method. This method takes a numeric value (negative or positive) as parameter, and returns a new Date and Time. I am adding a –ve (negative) value -1, since I want to check with previous dates. This is a simple method.

If you want to compare dates older than a month, then you can use the AddMonths() method and pass a negative value. For example,

DateTime.Now.AddMonths(-1))

👉 Do you know your .net application can delete images automatically that were created (or added) just 1 hour before using C#. Check out this article.
Delete images created 1 hour before in Asp.Net

Vb.Net

Here's the code for Vb developers.

Option Explicit On
Imports System.IO
Partial Class Site
    Inherits System.Web.UI.MasterPage

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        Dim files As String() = Directory.GetFiles(Server.MapPath("~/images/"))
        Dim iCnt As Integer = 0

        For Each file As String In files

            divList.InnerHtml = "Found: " & files.Length & " files."

            Dim info As New FileInfo(file)

            info.Refresh()

            If info.LastWriteTime <= DateTime.Now.AddDays(-1) Then
                info.Delete()
                iCnt += 1
            End If

            divList.InnerHtml = divList.InnerHtml & "<br > " & _
                iCnt & " files deleted."
        Next
    End Sub
End Class

← PreviousNext →