Reading from a file

If I want to open a file for reading, how do I check to first be sure the file exists?
MiradoAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AxterCommented:
Function FileExist(strDir As String) As Boolean
Dim tmpStr As String
tmpStr = Dir(strDir)
If Len(tmpStr) > 0 Then
    FileExist = True
    Else
    FileExist = False
    End If
End Function

Function PathExist(strDir As String) As Boolean
Dim tmpStr As String
tmpStr = Dir(strDir, vbDirectory)
If Len(tmpStr) > 0 Then
    PathExist = True
    Else
    PathExist = False
    End If
End Function
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
VbmasterCommented:
Actually that FileExist function WON'T work for some files (hidden, systems etc). Here's the correct and more compact code...

   Function FileExist(strDir As String) As Boolean

      FileExist = Len(Dir("D:\A.frm", vbArchive + vbHidden + vbReadOnly + vbSystem)) > 0)

   End Function

Another solution would be to use the FileLen function like this (just another way to do it)...

   Function FileExist(Filename As String) As Boolean

      On Error GoTo Errorhandler
 
      Call FileLen(Filename)
      FileExist = True
      Exit Function

   Errorhandler:
      FileExist = False

   End Function
0
AxterCommented:
Actually, you have some errors in your code.  You're missing the strDir variable and you have an extra brace at the end.
The following is the correct more compact version.

Function FileExist(strDir As String) As Boolean
      FileExist = Len(Dir(strDir, vbArchive + vbHidden + vbReadOnly + vbSystem)) > 0
End Function

0
MiradoAuthor Commented:
Thanks. That did just what I needed. The first reponse would have been fine for what I was needing but thanks for the added comment too.

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.