Results 1 to 13 of 13

Thread: CHECK if in dir are present 2 files, else msgobox

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Mar 2005
    Posts
    2,580

    CHECK if in dir are present 2 files, else msgobox

    pseudo code

    CHECK if in dir are present 2 files, else msgobox ="ALLERT!".... then unload me

    the dir is mydir, the file are:

    test.xls
    prov.txt

    naturally if one of this file exists, alert only for not exists file

  2. #2
    Hyperactive Member
    Join Date
    Jul 2020
    Posts
    370

    Re: CHECK if in dir are present 2 files, else msgobox

    Something like this:
    Code:
    Private Sub Form_Load()
    If nasFileExists("C:\autoexec.bat") Then        'Full path to the file.
      MsgBox "File exists ", vbInformation
     Else
      MsgBox "The file does not exist! ", vbCritical
     End If
    End Sub
    Public Function nasFileExists(FilePath As String) As Boolean
     On Error Resume Next
     Dim feFile
     Err.Clear
     feFile = FreeFile
     FilePath = Replace(FilePath, "\\", "\")
     Open FilePath For Input As #feFile
     If Err.Number = 53 Or Err.Number = 76 Then
      nasFileExists = False
      GoTo OK
     Else
      nasFileExists = True
     End If
    OK:
     Close #feFile
     Err.Clear
    End Function

  3. #3
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: CHECK if in dir are present 2 files, else msgobox

    Just trap errors on calls to the GetAttr function. If it fails then the file doesn't exist.

  4. #4
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,205

    Re: CHECK if in dir are present 2 files, else msgobox

    Why not just use the Dir$() function to see if the file is there?

  5. #5
    The Idiot
    Join Date
    Dec 2014
    Posts
    2,721

    Re: CHECK if in dir are present 2 files, else msgobox

    check https://www.vbforums.com/showthread....=1#post4454127

    important to understand that dir$ and getattr are not unicode compatible.
    better use API that can handle that.
    use GetFileAttributesW or FindFirstFileW
    even if u dont need unicode support, its best u learn to use that, so that if u need it in the future u already have it.

  6. #6

    Thread Starter
    PowerPoster
    Join Date
    Mar 2005
    Posts
    2,580

    Re: CHECK if in dir are present 2 files, else msgobox

    Quote Originally Posted by DataMiser View Post
    Why not just use the Dir$() function to see if the file is there?
    But i need to check if in my file wath is the missing, in dir...

  7. #7
    PowerPoster Arnoutdv's Avatar
    Join Date
    Oct 2013
    Posts
    5,872

    Re: CHECK if in dir are present 2 files, else msgobox

    So if it fails the file is not present..

  8. #8
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,205

    Re: CHECK if in dir are present 2 files, else msgobox

    Quote Originally Posted by luca90 View Post
    But i need to check if in my file wath is the missing, in dir...
    I do not know what you mean by that, a simple Dir$("C\MyFolder\MyFile.Txt") will do the trick if the file is not there it will return an empty string, if it is there it will return the filename.

  9. #9
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: CHECK if in dir are present 2 files, else msgobox

    For something this trivial calling Dir$() is fairly fat and floppy, and it interrupts any use of Dir$() already in progress. Avoid it.

    If you seriously live in a world where you must deal with Unicode filenames, then by all means use GetFileAttributesW() calls. This is seldom a problem for most people.

  10. #10
    Member
    Join Date
    Nov 2020
    Posts
    35

    Re: CHECK if in dir are present 2 files, else msgobox

    Quote Originally Posted by dilettante View Post
    For something this trivial calling Dir$() is fairly fat and floppy, and it interrupts any use of Dir$() already in progress. Avoid it.

    If you seriously live in a world where you must deal with Unicode filenames, then by all means use GetFileAttributesW() calls. This is seldom a problem for most people.
    you're right
    I always use DirW().
    (Not mine)



    Code:
    Option Explicit
    
    
    
    Private Const MAX_PATH = 260
    
    Public Enum VbFileAttributeExtended
        vbAll = -1&
        vbDirectory = 16& ' mean - include folders also
        vbFile = vbAll And Not vbDirectory
        vbSystem = 4&
        vbHidden = 2&
        vbReadOnly = 1
        vbNormal = 0&
        vbReparse = 1024& 'symlinks / junctions (not include hardlink to file; they reflect attributes of the target)
    End Enum
    #If False Then
        Dim vbAll, vbFile, vbReparse 'case sensitive protection against modification (for non-overloaded enum variables only)
    #End If
    
    Private Type FILETIME
        dwLowDateTime As Long
        dwHighDateTime As Long
    End Type
    Private Type WIN32_FIND_DATA
        dwFileAttributes As Long
        ftCreationTime As FILETIME
        ftLastAccessTime As FILETIME
        ftLastWriteTime As FILETIME
        nFileSizeHigh As Long
        nFileSizeLow As Long
        dwReserved0 As Long
        dwReserved1 As Long
        lpszFileName(MAX_PATH) As Integer
        lpszAlternate(14) As Integer
    End Type
    
    Private Const FILE_ATTRIBUTE_NORMAL As Long = &H80
    Private Const INVALID_HANDLE_VALUE As Long = -1
    
    Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileW" (ByVal lpFileName As Long, lpFindFileData As WIN32_FIND_DATA) As Long
    Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileW" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
    Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
    Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenW" (ByVal lpString As Long) As Long
    Private Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyW" (ByVal lpString1 As Long, ByVal lpString2 As Long) As Long
    
    Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesW" (ByVal lpFileName As Long) As Long
    Private Declare Function CreateDirectory Lib "kernel32" Alias "CreateDirectoryW" (ByVal lpPathName As Long, lpSecurityAttributes As Any) As Long
    Private Declare Function GetCurrentDirectory Lib "kernel32" Alias "GetCurrentDirectoryW" (ByVal nBufferLength As Long, ByVal lpBuffer As Long) As Long
    
    
    Public Function DirW( _
        Optional ByVal PathMaskOrFolderWithSlash As String, _
        Optional AllowedAttributes As VbFileAttributeExtended = vbNormal, _
        Optional FoldersOnly As Boolean) As String
    
        On Error GoTo ErrorHandler
    
        'WARNING note:
        'Original VB Dir$ contains bug: ReadOnly attribute incorrectly handled, so it always is in results
        'This sub properly handles 'RO' and also contains one extra flag: FILE_ATTRIBUTE_REPARSE_POINT (vbReparse)
        'Doesn't return "." and ".." folders.
        'Unicode aware
    
        Const MeaningfulBits As Long = &H417&   'D + H + R + S + Reparse
                                                '(to revert to default VB Dir behaviour, replace it by &H16 value)
    
        Dim fd      As WIN32_FIND_DATA
        Dim lpStr   As Long
        Dim lRet    As Long
        Dim Mask    As Long
    
        Static hFind        As Long
        Static lflags       As VbFileAttributeExtended
        Static bFoldersOnly As Boolean
    
        If hFind <> 0& And Len(PathMaskOrFolderWithSlash) = 0& Then
            If FindNextFile(hFind, fd) = 0& Then FindClose hFind: hFind = 0&: Exit Function
        Else
            If hFind Then FindClose hFind: hFind = 0&
            PathMaskOrFolderWithSlash = Trim(PathMaskOrFolderWithSlash)
            lflags = AllowedAttributes 'cache
            bFoldersOnly = FoldersOnly 'cache
    
            Select Case Right$(PathMaskOrFolderWithSlash, 1&)
            Case "\", ":", "/"
                PathMaskOrFolderWithSlash = PathMaskOrFolderWithSlash & "*.*"
            End Select
    
            hFind = FindFirstFile(StrPtr(PathMaskOrFolderWithSlash), fd)
    
            If hFind = INVALID_HANDLE_VALUE Then
                hFind = 0&
                If (Err.LastDllError) > 12& Then Err.Raise 52&
                Exit Function
            End If
        End If
    
        Do
            If fd.dwFileAttributes = FILE_ATTRIBUTE_NORMAL Then
                Mask = 0& 'found
            Else
                Mask = fd.dwFileAttributes And (Not lflags) And MeaningfulBits
            End If
            If bFoldersOnly Then
                If Not CBool(fd.dwFileAttributes And vbDirectory) Then
                    Mask = 1 'continue enum
                End If
            End If
    
            If Mask = 0 Then
                lpStr = VarPtr(fd.lpszFileName(0))
                DirW = String$(lstrlen(lpStr), 0&)
                lstrcpy StrPtr(DirW), lpStr
                If fd.dwFileAttributes And vbDirectory Then
                    If DirW <> "." And DirW <> ".." Then Exit Do 'exclude self and relative paths aliases
                Else
                    Exit Do
                End If
            End If
    
            If FindNextFile(hFind, fd) = 0 Then FindClose hFind: hFind = 0: Exit Function
        Loop
    
        Exit Function
    ErrorHandler:
        Debug.Print Err; Err.Description; "DirW"
    End Function

  11. #11
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,205

    Re: CHECK if in dir are present 2 files, else msgobox

    There is also a function included with VB5 and 6 called FileExists it is included in common.bas which is part of the code for setup1 under the pdwizard folder. They use the open for input method and check for error.

    My thoughts here were that if you are only checking for 2 files then Dir$() would be quick and easy, and on to the next issue. Of course there are many ways to determine if a file exists, some better than others and not all work in every case.

  12. #12
    PowerPoster
    Join Date
    Feb 2006
    Posts
    24,482

    Re: CHECK if in dir are present 2 files, else msgobox

    Yeah, there are plenty of ways.

  13. #13
    The Idiot
    Join Date
    Dec 2014
    Posts
    2,721

    Re: CHECK if in dir are present 2 files, else msgobox

    since I make tools & games that thousands download from all around the world I need to think about unicode or I get the usual run times errors when the program can't find a path or file.
    if the program is for private use and you know you have basic-ascii folder names, dir$ works well.
    but I do not understand experts saying its not needed and in other threads they expect people to use advanced methods.
    if VB6 would get an update most internal function would be updated to handle unicode. I would not dare create anything that I share to people that are not supporting unicode.

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