Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I delete all files in a folder except the 3 most recent? 1

Status
Not open for further replies.

AccessGuruCarl

Programmer
Jul 3, 2004
471
US
Hello,
How can I keep only 2 or 3 of the most recent files, and delete the rest.

I have an .mdb file ToolingFE.mdb(developers copy)
Which is copied to user folders when ever he makes code or form changes. If the file is not in use, it renames the file to the current date, removing the '/' and then copies the new file into users folder. - The Code Link Below...

The users folders will have files named as such,
ToolingFE.mdb, 2112007.mdb, 312007.mdb, 3222007.mdb, ect...
where the number format is date without the slashes.

What I need to do is:
Right after renaming the ToolingFE.mdb with the date, I want to delete everything else, but the 3 most recent copies. Then copy the new file in. This way the user can still have a copy of his last version, and the 2 previous.

Currently I'm using this script from an earlier post to rename and copy the file, and would like to expand on it to delete the old files.


Any Idea's.... Anyone.........

Thanks,


AccessGuruCarl
Programmers helping programmers
you can't find a better site.
 
One way you can do it is this.
[tt]
Const adVarChar = 200
Const adDate = 7

[green]ipreserve=3 '# of files to preserve
sfolderpath="d:\test" 'your path to the folder[/green]

set fso=createobject("scripting.filesystemobject")
if not fso.folderexists(sfolderpath) then
set fso=nothing
wscript.echo "The folder does not exist." & vbcrlf & sfolderpath & vbcrlf & "Operation aborted."
wscript.quit
end if

set ofolder=fso.getfolder(sfolderpath)
set rs = createobject("ador.recordset")
with rs.fields
.append "filepath",adVarChar,255
.append "datelastmodified",adDate
end with

with rs
.open
for each ofile in ofolder.files
.addnew array("filepath","datelastmodified"), array(ofile.path,ofile.datelastmodified)
.update
next
end with

icount=0
if not (rs.eof and rs.bof) then
rs.sort="datelastmodified desc"
rs.movefirst
do while not rs.eof
icount=icount+1
if icount>ipreserve then
on error resume next
fso.deletefile rs.fields("filepath"),true
on error goto 0
end if
rs.movenext
loop
end if

set rs=nothing
set ofolder=nothing
set fso=nothing
[/tt]
 

Great Post tsuji,

I was able to implement with ease.... and very little code adjustment!!!

Gave you 2 STARS!

AccessGuruCarl
Programmers helping programmers
you can't find a better site.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top