Results 1 to 21 of 21

Thread: Checking if a file exists

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Aug 2002
    Posts
    31

    Checking if a file exists

    Given the directory path and fielname, how do I check in VB if the file exists. If it doesn't exist when I check for it, then it should only return a value (eg 0, False, etc) and not crash my program with a Runtime Error.

    Thanks.

  2. #2
    Need-a-life Member Mc Brain's Avatar
    Join Date
    Apr 2000
    Location
    Buenos Aires, Argentina
    Posts
    6,808

    Asked a zillion times....

    Dir Function


    Returns a String representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.

    Syntax

    Dir[(pathname[, attributes])]

    The Dir function syntax has these parts:

    Part Description
    pathname Optional.String expression that specifies a file name — may include directory or folder, and drive. A zero-length string ("") is returned if pathname is not found.
    attributes Optional.Constant ornumeric expression, whose sum specifies file attributes. If omitted, returns files that match pathname but have no attributes.


    Settings

    The attributesargument settings are:

    Constant Value Description
    vbNormal 0 (Default) Specifies files with no attributes.
    vbReadOnly 1 Specifies read-only files in addition to files with no attributes.
    vbHidden 2 Specifies hidden files in addition to files with no attributes.
    VbSystem 4 Specifies system files in addition to files with no attributes.
    vbVolume 8 Specifies volume label; if any other attributed is specified, vbVolume is ignored.
    vbDirectory 16 Specifies directories or folders in addition to files with no attributes.


    Note These constants are specified by Visual Basic for Applications and can be used anywhere in your code in place of the actual values.

    Remarks

    Dir supports the use of multiple character (*) and single character (?) wildcards to specify multiple files.
    Figure it out yourself... the only way to learn.
    Emiliano F. Martín


    If a post has helped you then please Rate it! (and give the user points he/she deserves by clicking on the image).
    Encourage the person who helped you to keep doing it, and give him the points he deserves.


    MP3 Organizer: Freeware to logically organize all your MP3s.

  3. #3
    Evil Genius alex_read's Avatar
    Join Date
    May 2000
    Location
    Espoo, Finland
    Posts
    5,538
    VB Code:
    1. If Not (Len(Dir$("C:\boot.ini")) <> 0) Then
    2.     MsgBox "File Doesn't Exist!"
    3. Else
    4.     MsgBox "File Does Exist"
    5. End If

    Please rate this post if it was useful for you!
    Please try to search before creating a new post,
    Please format code using [ code ][ /code ], and
    Post sample code, error details & problem details

  4. #4
    Frenzied Member oh1mie's Avatar
    Join Date
    Sep 2001
    Location
    Finland
    Posts
    1,043
    DIR function do not work on network.
    You must use API for clear that.

    VB Code:
    1. Option Explicit
    2.  
    3. Private Const MAX_PATH As Long = 260
    4. Private Const INVALID_HANDLE_VALUE As Long = -1
    5.  
    6. Private Type FILETIME
    7.    dwLowDateTime As Long
    8.    dwHighDateTime As Long
    9. End Type
    10.  
    11. Private Type WIN32_FIND_DATA
    12.    dwFileAttributes As Long
    13.    ftCreationTime   As FILETIME
    14.    ftLastAccessTime As FILETIME
    15.    ftLastWriteTime  As FILETIME
    16.    nFileSizeHigh    As Long
    17.    nFileSizeLow     As Long
    18.    dwReserved0      As Long
    19.    dwReserved1      As Long
    20.    cFileName        As String * MAX_PATH
    21.    cAlternate       As String * 14
    22. End Type
    23.  
    24. Private Declare Function FindClose Lib "kernel32" _
    25.   (ByVal hFindFile As Long) As Long
    26.    
    27. Private Declare Function FindFirstFile Lib "kernel32" _
    28.    Alias "FindFirstFileA" _
    29.   (ByVal lpFileName As String, _
    30.    lpFindFileData As WIN32_FIND_DATA) As Long
    31. Public Function fcnFileExists(sSource As String) As Boolean
    32.  
    33.    Dim WFD   As WIN32_FIND_DATA
    34.    Dim hFile As Long
    35.    
    36.    hFile = FindFirstFile(sSource, WFD)
    37.    fcnFileExists = hFile <> INVALID_HANDLE_VALUE
    38.    
    39.    Call FindClose(hFile)
    40.    
    41. End Function
    oh1mie/Vic


  5. #5
    Addicted Member
    Join Date
    Aug 2002
    Location
    London UK
    Posts
    255
    Real simple way to do it:

    Call Len(File) and if it shoots up a runtime error, the file doesn't exist. You can catch that with the "On Error GoTo Label" statement.
    Not at all related to sheep...

  6. #6
    PowerPoster
    Join Date
    Aug 2000
    Location
    IN SILENCE
    Posts
    6,441

    Well

    Originally posted by A$$Bandit
    Real simple way to do it:

    Call Len(File) and if it shoots up a runtime error, the file doesn't exist. You can catch that with the "On Error GoTo Label" statement.
    Will this work for a network?
    Remaining quiet down here !!!

    BRAD HAS GIVEN ME THE ULTIMATIVE. I have chosen to stay....

  7. #7
    Need-a-life Member Mc Brain's Avatar
    Join Date
    Apr 2000
    Location
    Buenos Aires, Argentina
    Posts
    6,808
    Anyway, Opening the file (for input) and trapping the error always worked for me.
    Emiliano F. Martín


    If a post has helped you then please Rate it! (and give the user points he/she deserves by clicking on the image).
    Encourage the person who helped you to keep doing it, and give him the points he deserves.


    MP3 Organizer: Freeware to logically organize all your MP3s.

  8. #8
    Need-a-life Member Mc Brain's Avatar
    Join Date
    Apr 2000
    Location
    Buenos Aires, Argentina
    Posts
    6,808

    Re: Well

    Originally posted by James Stanich
    Will this work for a network?
    I don't understand what he tried to write... but, as it's written, that doesn't work at all.
    Emiliano F. Martín


    If a post has helped you then please Rate it! (and give the user points he/she deserves by clicking on the image).
    Encourage the person who helped you to keep doing it, and give him the points he deserves.


    MP3 Organizer: Freeware to logically organize all your MP3s.

  9. #9
    PowerPoster
    Join Date
    Aug 2000
    Location
    IN SILENCE
    Posts
    6,441

    Well

    oh1mie pointed out his way willl work when checking for existance over a network.

    Will Len(File) work over a network ?
    Remaining quiet down here !!!

    BRAD HAS GIVEN ME THE ULTIMATIVE. I have chosen to stay....

  10. #10
    Need-a-life Member Mc Brain's Avatar
    Join Date
    Apr 2000
    Location
    Buenos Aires, Argentina
    Posts
    6,808

    Re: Well

    Originally posted by James Stanich
    oh1mie pointed out his way willl work when checking for existance over a network.

    Will Len(File) work over a network ?
    I'm not sure about the Dir not working over a network. Anyway, the Len is for strings. That code does not work.

    Len Function


    Returns aLong containing the number of characters in a string or the number of bytes required to store avariable.

    Syntax

    Len(string | varname)

    The Len function syntax has these parts:

    Part Description
    string Any validstring expression. If string containsNull, Null is returned.
    Varname Any validvariable name. If varname contains Null, Null is returned. If varname is aVariant, Len treats it the same as a String and always returns the number of characters it contains.


    Remarks

    One (and only one) of the two possiblearguments must be specified. Withuser-defined types, Len returns the size as it will be written to the file.

    Note Use the LenB function with byte data contained in a string, as in double-byte character set (DBCS) languages. Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string. With user-defined types, LenB returns the in-memory size, including any padding between elements. For sample code that uses LenB, see the second example in the example topic.

    Note Len may not be able to determine the actual number of storage bytes required when used with variable-length strings in user-defineddata types.
    I mean.... it doesn't even work on files on your computer.
    Emiliano F. Martín


    If a post has helped you then please Rate it! (and give the user points he/she deserves by clicking on the image).
    Encourage the person who helped you to keep doing it, and give him the points he deserves.


    MP3 Organizer: Freeware to logically organize all your MP3s.

  11. #11
    Hyperactive Member
    Join Date
    Jun 2000
    Posts
    350
    Originally posted by Mc Brain
    Anyway, Opening the file (for input) and trapping the error always worked for me.
    File not found is error 53, btw
    .

  12. #12
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    I mean.... it doesn't even work on files on your computer.
    I think perhaps he didn't mean Len(File), but LOF(File)....

    As in ... LOF(1)...

    Either way, I have always used the API method, you stick in a module, and call it when you need it... if it the API method is good enough for Windows, its good enough for you.... go with API.

  13. #13
    Software Eng. Megatron's Avatar
    Join Date
    Mar 1999
    Location
    Canada
    Posts
    11,286
    If you don't need it to work over a network, then alex_read's method is the easiest.

  14. #14
    Fanatic Member Redth's Avatar
    Join Date
    May 2001
    Location
    Ontario, Canada
    Posts
    551
    looking quickly at the replies, i didn't see this api... i like to use this method in my projects:


    VB Code:
    1. Public Declare Function PathFileExists Lib "shlwapi.dll"
    2. Alias "PathFileExistsA" (ByVal pszPath As String) As Long
    3.  
    4. Public Function FileExists(strPath As String) As Boolean
    5.     If PathFileExists(strPath) = 1 Then
    6.         FileExists = True
    7.     Else
    8.         FileExists = False
    9.     End If
    10. End Function

    That's an easy way, and it too works on a network...

  15. #15
    Need-a-life Member Mc Brain's Avatar
    Join Date
    Apr 2000
    Location
    Buenos Aires, Argentina
    Posts
    6,808
    Originally posted by nemaroller
    I think perhaps he didn't mean Len(File), but LOF(File)....

    As in ... LOF(1)...

    Either way, I have always used the API method, you stick in a module, and call it when you need it... if it the API method is good enough for Windows, its good enough for you.... go with API.
    I thought so as well... but LOF needs the file to be opened. So, if the Open statement didn't raise any error, there's no need to check the lenght of that file.
    Emiliano F. Martín


    If a post has helped you then please Rate it! (and give the user points he/she deserves by clicking on the image).
    Encourage the person who helped you to keep doing it, and give him the points he deserves.


    MP3 Organizer: Freeware to logically organize all your MP3s.

  16. #16
    Need-a-life Member Mc Brain's Avatar
    Join Date
    Apr 2000
    Location
    Buenos Aires, Argentina
    Posts
    6,808
    Originally posted by Megatron
    If you don't need it to work over a network, then alex_read's method is the easiest.
    Anyway.. I've found that sometimes the "Dir way" locks the file in same way. For example, if you check if a file exist (with this code) and then you try to delete it.... you will not be able to do it.
    Emiliano F. Martín


    If a post has helped you then please Rate it! (and give the user points he/she deserves by clicking on the image).
    Encourage the person who helped you to keep doing it, and give him the points he deserves.


    MP3 Organizer: Freeware to logically organize all your MP3s.

  17. #17
    The picture isn't missing BuggyProgrammer's Avatar
    Join Date
    Oct 2000
    Location
    Vancouver, Canada
    Posts
    5,217
    and i think it's FileLen(), which returns the file size in bytes. not LOF() and Len()
    Remember, if someone's post was not helpful, you can always rate their post negatively .

  18. #18
    PowerPoster
    Join Date
    Jan 2001
    Location
    Florida
    Posts
    3,216
    Originally posted by Redth
    looking quickly at the replies, i didn't see this api... i like to use this method in my projects:


    VB Code:
    1. Public Declare Function PathFileExists Lib "shlwapi.dll"
    2. Alias "PathFileExistsA" (ByVal pszPath As String) As Long
    3.  
    4. Public Function FileExists(strPath As String) As Boolean
    5.     If PathFileExists(strPath) = 1 Then
    6.         FileExists = True
    7.     Else
    8.         FileExists = False
    9.     End If
    10. End Function

    That's an easy way, and it too works on a network...
    Perfect code!

  19. #19
    Super Moderator manavo11's Avatar
    Join Date
    Nov 2002
    Location
    Around the corner from si_the_geek
    Posts
    7,171
    It doesn't seem to work on XP. Also the line

    VB Code:
    1. Alias "PathFileExistsA" (ByVal pszPath As String) As Long

    has a problem i think...

    VB Code:
    1. Public Declare Function PathFileExists Lib "shlwapi.dll"
    2. Alias "PathFileExistsA" (ByVal pszPath As String) As Long
    3.  
    4. Public Function FileExists(strPath As String) As Boolean
    5.     If PathFileExists(strPath) = 1 Then
    6.         FileExists = True
    7.     Else
    8.         FileExists = False
    9.     End If
    10. End Function

  20. #20
    Need-a-life Member Mc Brain's Avatar
    Join Date
    Apr 2000
    Location
    Buenos Aires, Argentina
    Posts
    6,808
    Try:

    VB Code:
    1. Public Declare Function PathFileExists Lib "shlwapi.dll" [b]_[/b]
    2.   Alias "PathFileExistsA" (ByVal pszPath As String) As Long
    Emiliano F. Martín


    If a post has helped you then please Rate it! (and give the user points he/she deserves by clicking on the image).
    Encourage the person who helped you to keep doing it, and give him the points he deserves.


    MP3 Organizer: Freeware to logically organize all your MP3s.

  21. #21
    Super Moderator manavo11's Avatar
    Join Date
    Nov 2002
    Location
    Around the corner from si_the_geek
    Posts
    7,171
    You're right again McBrain.Thanks...

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