How to Check File Dates and Delete Older Files in a Directory
Keywords: fileymdhms timeymdhms timesubtract file date file time
Question:
I want to delete all files older than 4 days old in a directory. How do I do that?
Answer:
Here's some sample code:
This can be used without the Searcher Extender....
today = TimeYmdHms()
fivedaysago = TimeSubtract(today, "00:00:05:00:00:00")
Dirchange("C:\temp")
myfiles = FileItemize("*.*")
FileNum=ItemCount(myfiles, @tab)
For FileIndex=1 to FileNum
file=ItemExtract(FileIndex, myfiles, @tab)
getdate=FileYMDHMS(file)
if getdate <= fivedaysago
message("file is older than 4 days", file)
filedelete(file)
else
message("file is not older than 4 days", "file=%file%%@crlf%getdate=%getdate%%@crlf%fivedaysago=%fivedaysago%")
endif
next
This can be used WITH the Searcher Extender....
;-------------------------------------------------
;This example will delete files older than 30 days
;-------------------------------------------------
BoxOpen("File Deleter","Initializing")
AddExtender("Wsrch34I.dll");Searcher Extender DLL
timenow=TimeYmdHms() ;get current datetime
hand=srchInit("C:\Junk","*.*","","",16) ;initializes your search
x=0; initializes counter for display in box
while 1
file=srchNext(hand);gets first file
if file=="" then break ;if no more files break out of while loop
x=x+1 ; increments counter for display in box
timenow=TimeYmdHms();gets todays date
timeminus30 = TimeSubtract(timenow, "00:00:30:00:00:00") ;gets time 30 days ago
getfiletime=FileYmdHms(file);gets file time
;The following line can be used for debugging it displays all date varibles
;message("TimeNow %timenow%"," Is the 'Filetime' %getfiletime% <= 'Timeminus30(Thirty days ago)' %timeminus30% ?")
BoxText("%x% %file%") ;updates boxes text
;;;;; If getfiletime is older than timeminus30
if getfiletime <= timeminus30
string=strcat(x," ",file,@CRLF,"Over Thirty days old",@CRLF,"File being deleted!")
BoxText(string) ;updates boxes text
FileDelete(file) ;deletes the file
endif
timedelay(0.5);short pause
endwhile
srchFree(hand); frees search handle
Message("File Delete", "Completed.")
exit
Article ID: W13225
Filename: Check File Date and Delete Older Files in Directory.txt