Results 1 to 18 of 18

Thread: checking if a file exists

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2002
    Posts
    779

    Question checking if a file exists

    What would be the best way to figure out if a certain file exists? I was thinking about using the File System Objects. Does anybody know how to do this?

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: checking if a file exists

    Originally posted by bezaman
    What would be the best way to figure out if a certain file exists? I was thinking about using the File System Objects. Does anybody know how to do this?
    It's a little easier than that:

    eg:
    this will show a message if the file Test.Txt exists in the folder C:\Temp

    If Dir("c:\temp\test.txt") <> "" Then Msgbox "File Exists!"

  3. #3
    Frenzied Member ae_jester's Avatar
    Join Date
    Jun 2001
    Location
    Kitchener Ontario Canada Earth
    Posts
    1,545
    Here are some functions to check if a file or folder exist.

    VB Code:
    1. '*******************************************************************************
    2. '** Function:   FileExists
    3. '** Parameters:
    4. '**     FilePath (String) - the full path of a file
    5. '** Returns: True if the file exists, false otherwise
    6. '*******************************************************************************
    7. Public Function FileExists(FilePath As String) As Boolean
    8.     If Len(FilePath) = 0 Then
    9.         FileExists = False
    10.     Else
    11.         If Len(Dir$(FilePath)) > 0 Then
    12.             FileExists = True
    13.         Else
    14.             FileExists = False
    15.         End If
    16.     End If
    17. End Function
    18.  
    19.  
    20. '*******************************************************************************
    21. '** Function:   DirectoryExists
    22. '** Parameters:
    23. '**     DirectoryPath (String) - the full path of a directory
    24. '** Returns: True if the directory exists, false otherwise
    25. '*******************************************************************************
    26. Public Function DirectoryExists(DirectoryPath As String) As Boolean
    27.     If Len(DirectoryPath) = 0 Then
    28.         DirectoryExists = False
    29.     Else
    30.         If Len(Dir$(DirectoryPath, vbDirectory)) > 0 Then
    31.             DirectoryExists = True
    32.         Else
    33.             DirectoryExists = False
    34.         End If
    35.     End If
    36. End Function

  4. #4
    PowerPoster
    Join Date
    Feb 2001
    Location
    Crossroads
    Posts
    3,046
    Ive had mixed results using Dir for detecting presence of files (I have seen it "lie"). Anyway I came across this on the forums and it hasnt let me down yet:

    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

    Caveat is that shlwapi.dll will show up as a dependency and will be added to your install. When you try to install your app, Windows will complain about shlwapi.dll (in use I think). Anyway, just delete this dll from your install and youll be fine.

  5. #5
    Addicted Member
    Join Date
    Jul 2002
    Posts
    234
    I personally use this function (since as Muddy mentions, DIR will lie if you pass it a valid directory instead of a file without checking the attributes)

    VB Code:
    1. Private Type FILETIME
    2.    dwLowDateTime As Long
    3.    dwHighDateTime As Long
    4. End Type
    5.  
    6. Private Type WIN32_FIND_DATA
    7.   dwFileAttributes As Long
    8.   ftCreationTime As FILETIME
    9.   ftLastAccessTime As FILETIME
    10.   ftLastWriteTime As FILETIME
    11.   nFileSizeHigh As Long
    12.   nFileSizeLow As Long
    13.   dwReserved0 As Long
    14.   dwReserved1 As Long
    15.   cFileName As String * 260
    16.   cAlternate As String * 14
    17. End Type
    18.  
    19.  
    20. Private Declare Function FindFirstFile Lib "kernel32.dll" _
    21.                 Alias "FindFirstFileA" (ByVal lpFileName As String, _
    22.                 lpFindFileData As WIN32_FIND_DATA) As Long
    23. Private Declare Function FindClose Lib "kernel32.dll" _
    24.                 (ByVal hFindFile As Long) As Long
    25.  
    26. Public Function FindFile(ByVal sSource As String) As Boolean
    27.  
    28.      Dim hsearch As Long
    29.     Dim findinfo As WIN32_FIND_DATA  
    30.     Dim success As Long  
    31.     Dim Buffer As Long  
    32.     Dim retval As Long  
    33.    
    34.     ' Begin a file search:
    35.     hsearch = FindFirstFile(sSource, findinfo)
    36.     If hsearch = -1 Then  ' no files match the search string
    37.         FindFile = False
    38.     Else
    39.         FindFile = True
    40.     End If
    41.    
    42.      
    43.     ' Close the file search handle
    44.     retval = FindClose(hsearch)
    45.  
    46. End Function

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

    Well

    Or if you are still interested in the FSO way :

    VB Code:
    1. CHECKS FOR THE EXISTANCE OF A FILE
    2.  
    3. Function FILEEXISTS(ByVal lsFilename As String) As Boolean
    4.    
    5.     On Error Resume Next
    6.    
    7.     Dim FSO As New Scripting.FileSystemObject
    8.    
    9.     FILEEXISTS = FSO.FILEEXISTS(lsFilename)
    10.    
    11.     Set FSO = Nothing
    12.  
    13. End Function
    14.  
    15. ' CHECKS FOR THE EXISTANCE OF A FOLDER
    16.  
    17. Function FOLDEREXISTS(ByVal lsFilename As String) As Boolean
    18.    
    19.     On Error Resume Next
    20.    
    21.     Dim FSO As New Scripting.FileSystemObject
    22.    
    23.     FOLDEREXISTS = FSO.FOLDEREXISTS(lsFilename)
    24.    
    25.     Set FSO = Nothing
    26.  
    27. End Function
    Remaining quiet down here !!!

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

  7. #7
    Frenzied Member ae_jester's Avatar
    Join Date
    Jun 2001
    Location
    Kitchener Ontario Canada Earth
    Posts
    1,545
    I fixed the functions I posted before to behave correctly when checking directories....can anyone find anything wrong with them now?

    VB Code:
    1. '****************************************************
    2. '** Function:   FileExists
    3. '** Parameters:
    4. '**     FilePath (String) - the full path of a file
    5. '** Returns: True if the file exists, false otherwise
    6. '****************************************************
    7. Public Function FileExists(FilePath As String) As Boolean
    8.     If Len(FilePath) = 0 Then
    9.         FileExists = False
    10.     Else
    11.         If Len(Dir$(FilePath)) > 0 Then
    12.             'Make sure it's not a directory
    13.             If (GetAttr(FilePath) And vbDirectory) <> vbDirectory Then
    14.                 FileExists = True
    15.             Else
    16.                 FileExists = False
    17.             End If
    18.         Else
    19.             FileExists = False
    20.         End If
    21.     End If
    22. End Function
    23.  
    24.  
    25. '****************************************************
    26. '** Function:   DirectoryExists
    27. '** Parameters:
    28. '**     DirectoryPath (String) - the full path of a directory
    29. '** Returns: True if the directory exists, false otherwise
    30. '****************************************************
    31. Public Function DirectoryExists(DirectoryPath As String) As Boolean
    32.     If Len(DirectoryPath) = 0 Then
    33.         DirectoryExists = False
    34.     Else
    35.         If Len(Dir$(DirectoryPath, vbDirectory)) > 0 Then
    36.             If (GetAttr(DirectoryPath) And vbDirectory) = vbDirectory Then
    37.                 DirectoryExists = True
    38.             Else
    39.                 DirectoryExists = False
    40.             End If
    41.         Else
    42.             DirectoryExists = False
    43.         End If
    44.     End If
    45. End Function

  8. #8
    Member
    Join Date
    Apr 2003
    Location
    Singapore
    Posts
    42

    Question

    Hi guys,

    i have some slightly complicated issue with file exists.

    i need to check the file in multiple level directory structure.

    for eg :
    i have Directory MAIN
    also i have subfolders SUB1, SUB2 inside MAIN
    i would like to find a file "findfile.txt" in MAIN, SUB1 and SUB2 folders.

    say, i dont know how many subfolders available and also the names fo each folders. this is in my own server. nothing to do with user PC.

    is it possible ? if so pls guide me

    thanx in advance
    world is good..... people are bad...........but sometimes people are very good ! ! !

  9. #9
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974
    look at the DIR function in VB help - it has an example of seraching in sub folders that will do the job with some minor changes

  10. #10
    Member
    Join Date
    Apr 2003
    Location
    Singapore
    Posts
    42

    Smile

    Hi Geek,

    thanx for ur valuable suggestion.
    i was able to do it

    thanx guys !!!
    world is good..... people are bad...........but sometimes people are very good ! ! !

  11. #11
    Lively Member
    Join Date
    Sep 2002
    Location
    São Paulo, SP, Brasil
    Posts
    118

    Re: Well

    Originally posted by James Stanich
    Or if you are still interested in the FSO way :

    I just wish to add that, if you go on FSO way, you need to set the reference first. I got stuck few minutes looking for the right reference, so I though it might be relevant add this comment.

    To do it, just go on Project / References and select the "Microsoft Scripting Runtime" one, which shall be located on something like: C:\Windows\System\scrrun.dll
    --
    Cauê Cavalheiro Machado Rego

  12. #12
    Lively Member floppes's Avatar
    Join Date
    May 2001
    Location
    Darmstadt, Germany
    Posts
    99

    Exclamation Attention with Dir()!

    When you pass the path to a file on your CD-Rom drive to the Dir() function but you have no CD inserted, it will bring up a run-time error 52 (filename or -number wrong).

    So you better use one of the API functions

    I personally like the FindFirstFile() version best, because it works on all Windows versions and without any additional DLLs.

    Flo

    /edit: corrected the spelling
    Last edited by floppes; Sep 1st, 2003 at 08:40 AM.

  13. #13
    Hyperactive Member
    Join Date
    Nov 2002
    Location
    india
    Posts
    418
    hi,

    u can use filesystemobject to check whether file exists or not

    dim fs as new scripting.filesystemobject

    msgbox fs.fileexists("c:\test.txt")

  14. #14
    Member
    Join Date
    Aug 2003
    Posts
    63

    Look this

    Looking all the methods mencioned in this thread, I think you can use one that never fails:

    The "DIR" method can fail and the FSO or API method needs references.

    Try this one:

    VB Code:
    1. Public Function FileExist(strFilename As String) As Boolean
    2. On Error Resume Next
    3. If Len(strFilename) <= 0 Then FileExist = False: Exit Function
    4. Dim ff As Long
    5. ff = FreeFile()
    6. Open strFilename For Input As #ff
    7. If Err Then
    8. FileExist = False
    9. Else
    10. FileExist = True
    11. End If
    12. Close #ff
    13. End Function

    This method never fails (I had used it many times in A LOT of programs) and doesn't need any external declaration.

    Plz tell me what do you think.

    Andy

  15. #15
    Next Of Kin baja_yu's Avatar
    Join Date
    Aug 2002
    Location
    /dev/root
    Posts
    5,989
    I know this is an old thread but I have to bring this up.
    I have yet to find a way to determin if a folder exists but that it works on hidden folders. For instance they report that the folders like

    C:\Windows\Fonts
    C:\Documents and Settings\User\Cookies
    C:\Documents and Settings\User\Recent
    C:\Documents and Settings\User\SendTo

    etc...

    does anyone know a better way?

  16. #16
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709
    Ya, this is an old thread, but here is some code. You can parse the
    Users directory from the Favorites dir. Then you will know that
    the Cookies, etc. are in that folder too or use the second code
    example to get the users dir.

    VB Code:
    1. Const CSIDL_DESKTOP = &H0
    2. Const CSIDL_PROGRAMS = &H2
    3. Const CSIDL_CONTROLS = &H3
    4. Const CSIDL_PRINTERS = &H4
    5. Const CSIDL_PERSONAL = &H5
    6. Const CSIDL_FAVORITES = &H6
    7. Const CSIDL_STARTUP = &H7
    8. Const CSIDL_RECENT = &H8
    9. Const CSIDL_SENDTO = &H9
    10. Const CSIDL_BITBUCKET = &HA
    11. Const CSIDL_STARTMENU = &HB
    12. Const CSIDL_DESKTOPDIRECTORY = &H10
    13. Const CSIDL_DRIVES = &H11
    14. Const CSIDL_NETWORK = &H12
    15. Const CSIDL_NETHOOD = &H13
    16. Const CSIDL_FONTS = &H14
    17. Const CSIDL_TEMPLATES = &H15
    18. Const MAX_PATH = 260
    19. Private Type SHI TEMID 'TAKE SPACE OUT
    20.     cb As Long
    21.     abID As Byte
    22. End Type
    23. Private Type ITEMIDLIST
    24.     mkid As SHI TEMID 'TAKE SPACE OUT
    25. End Type
    26. Private Declare Function ShellAbout Lib "shell32.dll" Alias "ShellAboutA" (ByVal hWnd As Long, ByVal szApp As String, ByVal szOtherStuff As String, ByVal hIcon As Long) As Long
    27. Private Declare Function SHGetSpecialFolderLocation Lib "shell32.dll" (ByVal hwndOwner As Long, ByVal nFolder As Long, pidl As ITEMIDLIST) As Long
    28. Private Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
    29. Private Sub Form_Load()
    30.     'KPD-Team 1998
    31.     'URL: [url]http://www.allapi.net/[/url]
    32.     'E-Mail: [email][email protected][/email]
    33.     'Show an about window
    34.     ShellAbout Me.hWnd, App.Title, "Created by the KPD-Team 1999", ByVal 0&
    35.     'Set the graphical mode to persistent
    36.     Me.AutoRedraw = True
    37.     'Print the folders to the form
    38.     Me.Print "Start menu folder: " + GetSpecialfolder(CSIDL_STARTMENU)
    39.     Me.Print "Favorites folder: " + GetSpecialfolder(CSIDL_FAVORITES)
    40.     Me.Print "Programs folder: " + GetSpecialfolder(CSIDL_PROGRAMS)
    41.     Me.Print "Desktop folder: " + GetSpecialfolder(CSIDL_DESKTOP)
    42. End Sub
    43. Private Function GetSpecialfolder(CSIDL As Long) As String
    44.     Dim r As Long
    45.     Dim IDL As ITEMIDLIST
    46.     'Get the special folder
    47.     r = SHGetSpecialFolderLocation(100, CSIDL, IDL)
    48.     If r = NOERROR Then
    49.         'Create a buffer
    50.         Path$ = Space$(512)
    51.         'Get the path from the IDList
    52.         r = SHGetPathFromIDList(ByVal IDL.mkid.cb, ByVal Path$)
    53.         'Remove the unnecessary chr$(0)'s
    54.         GetSpecialfolder = Left$(Path, InStr(Path, Chr$(0)) - 1)
    55.         Exit Function
    56.     End If
    57.     GetSpecialfolder = ""
    58. End Function
    VB Code:
    1. Private Const TOKEN_QUERY = (&H8)
    2. Private Declare Function GetAllUsersProfileDirectory Lib "userenv.dll" Alias "GetAllUsersProfileDirectoryA" (ByVal lpProfileDir As String, lpcchSize As Long) As Boolean
    3. Private Declare Function GetDefaultUserProfileDirectory Lib "userenv.dll" Alias "GetDefaultUserProfileDirectoryA" (ByVal lpProfileDir As String, lpcchSize As Long) As Boolean
    4. Private Declare Function GetProfilesDirectory Lib "userenv.dll" Alias "GetProfilesDirectoryA" (ByVal lpProfileDir As String, lpcchSize As Long) As Boolean
    5. Private Declare Function GetUserProfileDirectory Lib "userenv.dll" Alias "GetUserProfileDirectoryA" (ByVal hToken As Long, ByVal lpProfileDir As String, lpcchSize As Long) As Boolean
    6. Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
    7. Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
    8. Private Sub Form_Load()
    9.     'KPD-Team 2000
    10.     'URL: [url]http://www.allapi.net/[/url]
    11.     'E-Mail: [email][email protected][/email]
    12.     Dim sBuffer As String, Ret As Long, hToken As Long
    13.     'set the graphics mode of this form to 'persistent'
    14.     Me.AutoRedraw = True
    15.     'create a string buffer
    16.     sBuffer = String(255, 0)
    17.     'retrieve the all users profile directory
    18.     GetAllUsersProfileDirectory sBuffer, 255
    19.     'show the result
    20.     Me.Print StripTerminator(sBuffer)
    21.     'create a string buffer
    22.     sBuffer = String(255, 0)
    23.     'retrieve the user profile directory
    24.     GetDefaultUserProfileDirectory sBuffer, 255
    25.     'show the result
    26.     Me.Print StripTerminator(sBuffer)
    27.     'create a string buffer
    28.     sBuffer = String(255, 0)
    29.     'retrieve the profiles directory
    30.     GetProfilesDirectory sBuffer, 255
    31.     'show the result
    32.     Me.Print StripTerminator(sBuffer)
    33.     'create a string buffer
    34.     sBuffer = String(255, 0)
    35.     'open the token of the current process
    36.     OpenProcessToken GetCurrentProcess, TOKEN_QUERY, hToken
    37.     'retrieve this users profile directory
    38.     GetUserProfileDirectory hToken, sBuffer, 255
    39.     'show the result
    40.     Me.Print StripTerminator(sBuffer)
    41. End Sub
    42. 'strips off the trailing Chr$(0)'s
    43. Function StripTerminator(sInput As String) As String
    44.     Dim ZeroPos As Long
    45.     ZeroPos = InStr(1, sInput, Chr$(0))
    46.     If ZeroPos > 0 Then
    47.         StripTerminator = Left$(sInput, ZeroPos - 1)
    48.     Else
    49.         StripTerminator = sInput
    50.     End If
    51. End Function
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  17. #17
    Next Of Kin baja_yu's Avatar
    Join Date
    Aug 2002
    Location
    /dev/root
    Posts
    5,989
    that is ok, but I dont need to find the path for the special folders I need to determin if a folder exists or not. I just wrote those as example because they are hidden.

  18. #18
    Next Of Kin baja_yu's Avatar
    Join Date
    Aug 2002
    Location
    /dev/root
    Posts
    5,989
    actually..... the FSO method works....

    so..if the original post author is here they can 'resolve' this ...

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