Results 1 to 7 of 7

Thread: Classic VB - How can I check if a file exists?

  1. #1

    Thread Starter
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Classic VB - How can I check if a file exists?

    Visual basic has a built-in function called Dir which lists files for you, based on options you specify.

    If you specify a full filename (and path) it will return the filename if the file exists. If the specified file doesn't

    exist, an empty string "" will be returned.

    To find the file C:\Test.txt you would do the following:
    VB Code:
    1. If Dir("C:\Test.txt") <> "" Then
    2.   Msgbox "File exists"
    3. Else
    4.   Msgbox "File does not exist"
    5. End If
    If the file has special attributes (eg: is Hidden) you need to specify this too, eg:
    VB Code:
    1. If Dir("C:\Test.txt", vbHidden) <> "" Then
    2.   Msgbox "File exists"
    3. End If


    Here is a function you can use which returns True if the specified file exists (or False if it doesn't).
    VB Code:
    1. Private Function CheckPath(strPath As String) As Boolean
    2.     If Dir$(strPath) <> "" Then
    3.         CheckPath = True
    4.     Else
    5.         CheckPath = False
    6.     End If
    7. End Function
    Just call the above function with the path of the file to check as its parameter.



    Cheers,

    RyanJ
    Last edited by si_the_geek; Jul 24th, 2007 at 05:14 PM. Reason: added explanation, tidied up, and corrected code

  2. #2
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Arrow Re: Classic VB - How can I check if a file exists?

    For the ultimate reliable way to determine if a file exists, any file attributes like vbHidden, vbSystem, or any combination of any other file attributes will not affect the results ...

    VB Code:
    1. 'In a standard Module: Module1.bas
    2. Option Explicit
    3.  
    4. Private Const OF_EXIST         As Long = &H4000
    5. Private Const OFS_MAXPATHNAME  As Long = 128
    6. Private Const HFILE_ERROR      As Long = -1
    7.  
    8. Private Type OFSTRUCT
    9.     cBytes As Byte
    10.     fFixedDisk As Byte
    11.     nErrCode As Integer
    12.     Reserved1 As Integer
    13.     Reserved2 As Integer
    14.     szPathName(OFS_MAXPATHNAME) As Byte
    15. End Type
    16.  
    17. Private Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String, _
    18.                         lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long
    19.  
    20. Public Function FileExists(ByVal Fname As String) As Boolean
    21.  
    22.     Dim lRetVal As Long
    23.     Dim OfSt As OFSTRUCT
    24.    
    25.     lRetVal = OpenFile(Fname, OfSt, OF_EXIST)
    26.     If lRetVal <> HFILE_ERROR Then
    27.         FileExists = True
    28.     Else
    29.         FileExists = False
    30.     End If
    31.    
    32. End Function
    VB Code:
    1. 'Usage:
    2. 'Behind Form1:
    3. Option Explicit
    4.  
    5. Private Sub Form_Load()
    6.     MsgBox FileExists("C:\Test.txt") 'True :D
    7. End Sub
    Enjoy!

    VB/Office Guru™ ®
    Last edited by si_the_geek; May 23rd, 2006 at 05:29 AM.

  3. #3
    PowerPoster RhinoBull's Avatar
    Join Date
    Mar 2004
    Location
    New Amsterdam
    Posts
    24,132

    Re: Classic VB - How can I check if a file exists?

    There is always a FileSystemObject (scripting library).
    Coinsidentally (with what Rob has posted) it also has FileExists function that returns boolean:
    VB Code:
    1. Private Sub Command1_Click()
    2. '============================
    3. Dim fso As FileSystemObject
    4. Dim sFilePath As String
    5.  
    6.     Set fso = New FileSystemObject
    7.    
    8.     sFilePath = "c:\test.txt"
    9.     If fso.FileExists(sFilePath) Then
    10.         MsgBox "File Exist."
    11.     Else
    12.         MsgBox "File Doesn't Exist."
    13.     End If
    14.  
    15. End Sub
    Last edited by si_the_geek; May 27th, 2006 at 06:08 PM.

  4. #4
    PowerPoster
    Join Date
    Jun 2001
    Location
    Trafalgar, IN
    Posts
    4,141

    Re: Classic VB - How can I check if a file exists?

    I have always found the GetAttr function to be a good quick way to check the existence of a file.
    Code:
    Private Sub Command1_Click()
        Debug.Print FileExists("C:\somefile.txt")
    End Sub
    
    Private Function FileExists(ByVal sFileName As String) As Boolean
    Dim intReturn As Integer
    
        On Error GoTo FileExists_Error
        intReturn = GetAttr(sFileName)
        FileExists = True
        
    Exit Function
    FileExists_Error:
        FileExists = False
    End Function

  5. #5
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,123

    Arrow Re: Classic VB - How can I check if a file exists?

    We can also utilize the API's FindFirstFile and FindNextFile to determine the existence of a file or a folder, it can also support wildcard searches which I demonstrate here.

    vb Code:
    1. 'In a standard Module
    2. Option Explicit
    3.  
    4. Public Const MAX_PATH                   As Long = 260
    5. Private Const ERROR_NO_MORE_FILES       As Long = 18&
    6. Private Const FILE_ATTRIBUTE_NORMAL     As Long = &H80
    7.  
    8. Private Type FILETIME
    9.     dwLowDateTime   As Long
    10.     dwHighDateTime  As Long
    11. End Type
    12.  
    13. Private Type WIN32_FIND_DATA
    14.     dwFileAttributes    As Long
    15.     ftCreationTime      As FILETIME
    16.     ftLastAccessTime    As FILETIME
    17.     ftLastWriteTime     As FILETIME
    18.     nFileSizeHigh       As Long
    19.     nFileSizeLow        As Long
    20.     dwReserved0         As Long
    21.     dwReserved1         As Long
    22.     cFileName           As String * MAX_PATH
    23.     cAlternate          As String * 14
    24. End Type
    25.  
    26. Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" ( _
    27.                 ByVal lpFileName As String, _
    28.                 lpFindFileData As WIN32_FIND_DATA) As Long
    29. Private Declare Function FindClose Lib "kernel32" ( _
    30.                 ByVal hFindFile As Long) As Long
    31. Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" ( _
    32.                 ByVal hFindFile As Long, _
    33.                 lpFindFileData As WIN32_FIND_DATA) As Long
    34.  
    35. Public Function FileExists(ByVal sFile As String) As Boolean
    36.     Dim lpFindFileData  As WIN32_FIND_DATA
    37.     Dim lFileHandle     As Long
    38.     Dim lRet            As Long
    39.     Dim sTemp           As String
    40.     Dim sFileExtension  As String
    41.     Dim sFileName       As String
    42.     Dim sFileData()     As String
    43.     Dim sFileToCompare  As String
    44.    
    45.     If IsDirectory(sFile) = True Then
    46.         sFile = AddSlash(sFile) & "*.*"
    47.     End If
    48.    
    49.     If InStr(sFile, ".") > 0 Then
    50.         sFileToCompare = GetFileTitle(sFile)
    51.         sFileData = Split(sFileToCompare, ".")
    52.         sFileName = sFileData(0)
    53.         sFileExtension = sFileData(1)
    54.     Else
    55.         Exit Function
    56.     End If
    57.    
    58.     ' get a file handle
    59.     lFileHandle = FindFirstFile(sFile, lpFindFileData)
    60.     If lFileHandle <> -1 Then
    61.         If sFileName = "*" Or sFileExtension = "*" Then
    62.             FileExists = True
    63.         Else
    64.             Do Until lRet = ERROR_NO_MORE_FILES
    65.                 ' if it is a file
    66.                 If (lpFindFileData.dwFileAttributes And FILE_ATTRIBUTE_NORMAL) = vbNormal Then
    67.                     sTemp = StrConv(RemoveNull(lpFindFileData.cFileName), vbProperCase)
    68.                    
    69.                     'remove LCase$ if you want the search to be case sensitive
    70.                     If LCase$(sTemp) = LCase$(sFileToCompare) Then
    71.                         FileExists = True ' file found
    72.                         Exit Do
    73.                     End If
    74.                 End If
    75.                 'based on the file handle iterate through all files and dirs
    76.                 lRet = FindNextFile(lFileHandle, lpFindFileData)
    77.                 If lRet = 0 Then Exit Do
    78.             Loop
    79.         End If
    80.     End If
    81.    
    82.     ' close the file handle
    83.     lRet = FindClose(lFileHandle)
    84. End Function
    85.  
    86. Private Function IsDirectory(ByVal sFile As String) As Boolean
    87.     On Error Resume Next
    88.     IsDirectory = ((GetAttr(sFile) And vbDirectory) = vbDirectory)
    89. End Function
    90.  
    91. Private Function RemoveNull(ByVal strString As String) As String
    92.     Dim intZeroPos As Integer
    93.  
    94.     intZeroPos = InStr(strString, Chr$(0))
    95.     If intZeroPos > 0 Then
    96.         RemoveNull = Left$(strString, intZeroPos - 1)
    97.     Else
    98.         RemoveNull = strString
    99.     End If
    100. End Function
    101.  
    102. Public Function GetFileTitle(ByVal sFileName As String) As String
    103.     GetFileTitle = Right$(sFileName, Len(sFileName) - InStrRev(sFileName, "\"))
    104. End Function
    105.  
    106. Public Function AddSlash(ByVal strDirectory As String) As String
    107.     If InStrRev(strDirectory, "\") <> Len(strDirectory) Then
    108.         strDirectory = strDirectory + "\"
    109.     End If
    110.     AddSlash = strDirectory
    111. End Function

    Sample Usage:
    VB Code:
    1. 'specific file
    2. If FileExists("C:\WINDOWS\system32\progman.exe") Then
    3.     MsgBox "Existing!"
    4. Else
    5.     MsgBox "Not Existing!"
    6. End If
    7.  
    8. 'check existence of folder
    9. If FileExists("C:\Program Files") Then
    10.     MsgBox "Existing!"
    11. Else
    12.     MsgBox "Not Existing!"
    13. End If
    14.  
    15. 'wildcard search1
    16. If FileExists("C:\WINDOWS\system32\pschdprf.*") Then
    17.     MsgBox "Existing!"
    18. Else
    19.     MsgBox "Not Existing!"
    20. End If
    21.  
    22. 'wildcard search2
    23. If FileExists("C:\WINDOWS\system32\*.dll") Then
    24.     MsgBox "Existing!"
    25. Else
    26.     MsgBox "Not Existing!"
    27. End If
    28.  
    29. 'wildcard search3
    30. If FileExists("C:\WINDOWS\*.*") Then
    31.     MsgBox "Existing!"
    32. Else
    33.     MsgBox "Not Existing!"
    34. End If
    Last edited by dee-u; Jan 7th, 2009 at 11:02 PM. Reason: Added support for searching folders and wildcard searches
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  6. #6
    Member
    Join Date
    May 2006
    Posts
    61

    Re: Classic VB - How can I check if a file exists?

    Just a tip... don't use the dir function to check if files exist.
    It will muck up any other functions you have which use dir in a loop.

    David

  7. #7
    Default Member Bonnie West's Avatar
    Join Date
    Jun 2012
    Location
    InIDE
    Posts
    4,060

    Re: Classic VB - How can I check if a file exists?

    Here's yet another reason to avoid Dir:

    Quote Originally Posted by Bonnie West View Post
    Note that the Dir function may return a filename when an empty or null string is passed to it. The GetAttr function is better (and faster) in this regard:

    Code:
    Public Function FileExists(ByRef sFileName As String) As Boolean
        On Error Resume Next
        FileExists = (GetAttr(sFileName) And vbDirectory) <> vbDirectory
        On Error GoTo 0
    End Function
    The Unicode version of the underlying API is even faster (on NT-based OSs):

    Code:
    Private Declare Function GetFileAttributesW Lib "kernel32.dll" (ByVal lpFileName As Long) As Long
    
    Public Function FileExists(ByRef sFileName As String) As Boolean
        Const ERROR_SHARING_VIOLATION = 32&
    
        Select Case (GetFileAttributesW(StrPtr(sFileName)) And vbDirectory) = 0&
            Case True: FileExists = True
            Case Else: FileExists = Err.LastDllError = ERROR_SHARING_VIOLATION
        End Select
    End Function



    References:

    Last edited by Bonnie West; Feb 7th, 2016 at 03:53 AM.
    On Local Error Resume Next: If Not Empty Is Nothing Then Do While Null: ReDim i(True To False) As Currency: Loop: Else Debug.Assert CCur(CLng(CInt(CBool(False Imp True Xor False Eqv True)))): Stop: On Local Error GoTo 0
    Declare Sub CrashVB Lib "msvbvm60" (Optional DontPassMe As Any)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width