Compare two files in two different folders and replace them with new ones
With this VBScript code, I was able to copy the files. If the file exists, it does nothing unless it copies the required files.
Dim Photo
SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"
Set ObjPhoto = CreateObject("Scripting.FileSystemObject")
For Each Photo In ObjPhoto.GetFolder( SourceFolder).Files
If Not ObjPhoto.FileExists(ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))) Then
photo.Copy ObjPhoto.BuildPath(DistinationFolder, Photo.Name), True
End If
Next
I want to compare files if the source files also exist in the destination folder and replace it with the new one.
source to share
If you want to copy on the basis of the last modified date, the object File
has a property that you want: DateLastModified
. (You can check all properties of the object File
here .)
You already have access to the objects in the source file (your variable Photo
), so you just need to get the target file.
Something like this should work:
Dim Photo
Dim targetFile, bmpTargetFilename, jpgTargetFilename
SourceFolder = "C:\Photo1"
DistinationFolder = "C:\Photo2"
Set ObjPhoto = CreateObject("Scripting.FileSystemObject")
For Each Photo In ObjPhoto.GetFolder(SourceFolder).Files
bmpTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Replace(Photo.Name, ".jpg", ".bmp"))
jpgTargetFilename = ObjPhoto.BuildPath(DistinationFolder, Photo.Name)
If ObjPhoto.FileExists(bmpTargetFilename) Then
' Get the target file object
Set targetFile = ObjPhoto.GetFile(jpgTargetFilename)
' Now compare the last modified dates of both files
If Photo.DateLastModified > targetFile.DateLastModified Then
Photo.Copy jpgTargetFilename, True
End If
Else
Photo.Copy jpgTargetFilename, True
End If
Next
A few notes:
- You seem to be checking for the existence of the .BMP file, but by copying the .JPG file, so I made it explicit using two variables.
- I also assume that you want to compare JPG files as they are being copied.
source to share