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. I have provided the link to the tool at the bottom of this post and every page in this blog. What started as an experiment, has gained some popularity among online users and it’s now serving 200 users every day, processing 250 pictures at an average, and this figure is steadily rising.

Did I said, “Serving 200 users (as of Nov 2016) every day”. Yes, that’s right. Now, It is not a figure that will make me jump of my seat. However, there was a small issue, which demanded some immediate attention and action.

Once the images are processed, users download a copy of their 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 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);


            if (info.LastWriteTime <= DateTime.Now.AddDays(-1))
                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.

Also Read: Get all Files from a Folder and Bind with a GridView control in Asp.Net C#

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,



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)


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

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

That’s it. I am sure this article and its example would help you figure out how to get rid of old files in a folder using Asp.Net. Thanks for reading.

← PreviousNext →