Skip to main content
Inspiring
May 12, 2009
Answered

Query a Directory and delete all files more than 1 hour old

  • May 12, 2009
  • 1 reply
  • 1162 views

How would I query a directory and delete all files from that directory that are more than 1 hour old?

I have used CFDIRECTORY before to post pages to the directory and to get directory info but I cant figure out how to query a directory and delete all files more than 1 hour old from that directory.

1 hour old means that the time NOW is more than an hour from the file's date/time on the server.

    This topic has been closed for replies.
    Correct answer ilssac

    You need to user a combonation of the <cfdirectory...> tag to read the files and the <cffile ...> to delete the files in conjuction of a <cfif> tag to decide when and when not to do the deletion.  The dateDiff function would be handy in that decision.

    In pseduo code:

    <cfdirectory directory="theDir" name="theFiles"...>

    <cfloop query="theFiles">

       <cfif dateDiif(theFiles,now(),'h") GT 1>

         <cffile action="delete" file="theFiles.name"...>

      </cfif>

    </cfloop>

    NOTE:  Pay close attention to how the dateDiff works with fractional amounts.  I.E 59 minutes and 59 seconds is 0 hours while 1 hour and 1 second is 1 hour with the 'h' percision value.

    Also note that I did NOT look up the syntax for any of these tags and I probably misnamed and|or misorderd the parameters.

    1 reply

    ilssac
    ilssacCorrect answer
    Inspiring
    May 12, 2009

    You need to user a combonation of the <cfdirectory...> tag to read the files and the <cffile ...> to delete the files in conjuction of a <cfif> tag to decide when and when not to do the deletion.  The dateDiff function would be handy in that decision.

    In pseduo code:

    <cfdirectory directory="theDir" name="theFiles"...>

    <cfloop query="theFiles">

       <cfif dateDiif(theFiles,now(),'h") GT 1>

         <cffile action="delete" file="theFiles.name"...>

      </cfif>

    </cfloop>

    NOTE:  Pay close attention to how the dateDiff works with fractional amounts.  I.E 59 minutes and 59 seconds is 0 hours while 1 hour and 1 second is 1 hour with the 'h' percision value.

    Also note that I did NOT look up the syntax for any of these tags and I probably misnamed and|or misorderd the parameters.