ASP Tutorials - Deleting temporary files by checking their age

This example builds on some of the techniques described in other tutorials for listing file properties and deleting files.


Often an ASP application can be used to create temporary files and it can be difficult to guarantee that these files will be removed afterwards. The following technique is a simple and effective way to make sure that files can be emoved from a directory periodically. It lists all the files in the directory and compares the date each file was created against the current date and time. In our code, the file will be deleted if it is more than one day old, although this time period can be set to some other value.

The code requires a physical path to the file so we have used Server.MapPath to find the path of a folder. A physical path could be hard coded instead.

Set FSO = Server.CreateObject("Scripting.FileSystemObject")
Set AFolder = FSO.GetFolder(Server.MapPath("tempfiles"))
For Each Item in AFolder.Files
  If DateDiff("d", Item.DateCreated, Now) > 0 Then
    FSO.DeleteFile Item
  End If

The For..Each loop looks at each file in the folder and compares the DateCreated property of the file with the value of Now, which is the current date/time. DateDiff is used for date and time comparisions and its first parameter is a constant which determines the date and time period to use for units. The following values can be used. They are strings and so they must be enclosed in quotes.

yyyy - Year
q - Quarter
m - Month
y - Day of year
d - Day
w - Week day
ww - Week of year
h - Hour
n - Minute
s - Second

This method for deleting files must only be used when the directory contains only files which are to be deleted. If there are important files, such as scripts, they would be dleted as well. It is important that when temporary files are created as part of the application, they must be kept in a directory of their own.

This code could be placed in a script which is run periodically, either manually or as a Scheduled Task. There is no reason why it cannot be placed inside another script that is part of the application so that the temporary files in the directory are cleared as it runs.

Click here for more on using Server.MapPath to find physical paths.


The sample code in these tutorials is written for VBScript in classic ASP unless otherwise stated. The code samples can be freely copied.