Solarum – Information For Everyone

Jul

See if a file exists in Visual Basic

  Print Print

Here is a handy little tip (and function) for all you Visual Basic developers out there.  I use this quite often, it’s useful to see if whatever file you are working with or looking for exists before you start trying to access it.  So, here we have a nice little function you can drop into a module and call from anywhere when you need it.

(Need to do the same for a directory? That function is here!)

Check it out:

Public Function fFileExists(ByVal FileName As String) As Boolean
 
        Dim TempAttr As Integer
        On Error GoTo ErrorFileExist
                TempAttr = GetAttr(FileName)
                fFileExists = ((TempAttr And vbDirectory) = 0)
                GoTo ExitFileExist
 
ErrorFileExist:
        fFileExists = False
        Resume ExitFileExist
 
ExitFileExist:
        On Error GoTo 0
 
End Function

There you have it!  Just call it in an IF statement like so:

if fFileExists("c:\temp\myfile.txt") then
  ' Hey, it's there
else
  ' Nope, no file here
end if

It’s just that easy, enjoy!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Technorati
  • Slashdot
  • Fark
  • blogmarks
  • email
  • Facebook
  • LinkedIn
  • Live
  • TwitThis
  1. See If A Directory Exists In Visual Basic | Solarum - Information For Everyone Said,

    [...] how about a close cousin to yesterdays Visual Basic function?  In a previous post we showed you a function that will tell you whether or not a file does indeed exist.  Well, here is another similar function, but it tells you whether or not a directory exists. [...]

Add A Comment

Pages

Articles