Results 1 to 7 of 7

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

Threaded View

  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

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