DirExact()

One problem with the Win32 API file finding functions (and thus the VB Dir() function) is that they don't work quite correctly for files that have extensions longer than 3 characters. For example, Dir("c:\*.html") will not just return all .HTML files, but also all .HTM ones. The function below provides a workaround and is syntax-compatible with the regular Dir() function:

Function DirExact(Optional ByVal Mask As String = "") As String

Dim tmp As String
Static PrevMask As String, ExtLen As Integer, Ext As String

'//Is this a 'Get First File' operation? If so, save the file mask for
'//future use, and initialize the vars used to check the extension
If Mask <> "" Then
   PrevMask = Mask
   ExtLen = Len(Mask) - InStr(Mask, ".") + 1
   Ext = LCase(Right(Mask, ExtLen))
End If

'//Do the actual dir operation
Do
   If Mask <> "" Then
       tmp = Dir(Mask)
       Mask = ""
'//...to make sure the next op is 'get next'...
   Else
       tmp = Dir
   End If
'//Unless no file was found, or the extension matched exactly, try again
Loop While tmp <> "" And LCase(Right(tmp, ExtLen)) <> Ext

DirExact = tmp

End Function

 

[Home] [Publications] [Code] [Contact Us] [Legal]