How to Delete Images in a folder Older than 1 Hour in Asp.Net using C# and VB

← PrevNext →

Let us assume, you are using Asp.Net and there is a folder full of images and you want to delete images automatically that were created (or added) 1 hour before. You can use the Delete() method of the FileInfo class to delete files or images in a folder. But, how do you check when exactly the images were created or added in the folder? Let’s find out.

There are two important methods in Asp.Net that you’ll need to use to figure out when the images were created (1 hour before, 5 hours before or 1 day before. The first is a property named LastWriteTime and second is a method called AddHours().

Let’s see a working example first.

C# Code
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)
        {
            // Show how many files in the folder.
            divList.InnerHtml = "Found: " + files.Length + " files.";

            FileInfo info = new FileInfo(file);

            info.Refresh();

            // Check when files where created or added.
            if (info.LastWriteTime <= DateTime.Now.AddHours(-1))    
            {
                // Now check if its an image file.
                switch(info.Extension) {
                    case ".png" : 
                    case ".jpg" :
                    case ".bmp":
                    case ".jpeg":
                    case ".gif":
                        info.Delete();      // Delete the images.
                        iCnt += 1;
                        break;
                }
            }

            // Show how many files deleted.
            divList.InnerHtml = divList.InnerHtml + "<br > " + iCnt + " files deleted.";
        }
    }
}

First, I need to fetch the files in a given folder. The System.IO namespace (in the beginning of the code) provides all the necessary methods and properties to get folder and file details for a given path.

Once I get the files, I’ll iterate through each file and check when the file was created or added in the folder.

if (info.LastWriteTime <= DateTime.Now.AddHours(-1))

The LastWriteTime property gets or sets the time when the file (or directory) was last written to (or when the file was modified). The AddHours() method returns a time and here it has a parameter, -1, which returns the time before one hour. So now, I can easily check if the files where created or added an hour ago.

Note: Change the parameter value of the AddHours() according to your requirement. For example, if its 5 hours before, use

DateTime.Now.AddHours(-5)

Ok, I want to delete images only and if it was created 1 hour before. So, I must check the extension of each file and see if its an image file. If true, it will delete the image, automatically.

switch(info.Extension) {
    case ".png" : 
    case ".jpg" :
    case ".bmp":
    case ".jpeg":
    case ".gif":
        info.Delete();      // Delete the images.
Here’s the code in VB
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

            ' Show how many files in the folder.
            divList.InnerHtml = "Found: " & files.Length & " files."

            Dim info As New FileInfo(file)

            info.Refresh()

            ' Check when files where created or added.
            If info.LastWriteTime <= DateTime.Now.AddHours(-1) Then
                Select Case (info.Extension)
                    ' Now check if its an image file.
                    Case ".png", ".jpg", ".bmp", ".jpeg", ".gif"
                        info.Delete()      ' Delete the images.
                        iCnt += 1
                End Select
            End If

            ' Show how many files deleted.
            divList.InnerHtml = divList.InnerHtml & "<br > " & iCnt & " files deleted."
        Next
    End Sub
End Class

You can apply this method to delete any type of files in a given folder. Don’t forget to add a message before deleting any file. Give users a choice.

← PreviousNext →