Search code examples
vbscriptfile-existsfilesystemobject

VBS FileSystem Object - FileExists, comparing more than just the filename


I have a script that periodically downloads information from an RSS feed, one of which being an image. Right now, I'm checking to see if the image exists before I download it using the FileSystemObject and the FileExists comparison so that I'm not constantly downloading the same file over and over. Periodically, the image will update, but keep the same name, but after running some tests, it looks like FileExists just compares the filenames, not the actual file. Since the file online and the file locally have the same name, it won't download the image even though they are different images.

My question is is there another way to compare files to see if they're different despite the names?

This is the function I'm using:

function saveImageReturnPath(oPath)
dim oFSO
dim oHTTP
dim oStream
dim fol
dim fil

set oFSO = createObject("Scripting.FileSystemObject")
fil = oFSO.getBaseName(oPath) & ".jpg"

if not oFSO.fileExists(localPath & fil) then
    set oHTTP = createObject("MSXML2.XMLHTTP")
    oHTTP.open "GET", oPath, false
    oHTTP.send
    set oStream = createObject("ADODB.Stream")
    oStream.type = 1
    oStream.open
    oStream.write oHTTP.responseBody
    oStream.saveToFile oFSO.buildPath(localPath, fil), 2
    oStream.close
end if

saveImageReturnPath = localPath & fil
end function

Solution

  • You could check the MD5 hash of the file.

    See this question for details on how to implement this.

    Set fso = CreateObject("Scripting.FileSystemObject")
    Dim oMD5:  Set oMD5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
    
    Function GetMd5(filename)
        Dim oXml, oElement
    
        oMD5.ComputeHash_2(GetBinaryFile(filename))
    
        Set oXml = CreateObject("MSXML2.DOMDocument")
        Set oElement = oXml.CreateElement("tmp")
        oElement.DataType = "bin.hex"
        oElement.NodeTypedValue = oMD5.Hash
        GetMd5 = oElement.Text
    End Function
    

    Disclaimer: I did not test this code, it is the code from the linked answer. I posted it in case the answer gets deleted or the link breaks.