Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File Exists

Status
Not open for further replies.

gamechampionx

Programmer
Jan 26, 2002
14
0
0
CA
How do you determine whether or not a given file exists?
 
If Dir(&quot;C:\Test.txt&quot;) <> &quot;&quot; Then
MsgBox &quot;File Exists&quot;
Else
MsgBox &quot;File Does Not Exist&quot;
End If
 
Use the Dir function that is built into VB.

You should have this in your help file.

Dir Function Example
This example uses the Dir function to check if certain files and directories exist.

Dim MyFile, MyPath, MyName
' Returns &quot;WIN.INI&quot; if it exists.
MyFile = Dir(&quot;C:\WINDOWS\WIN.INI&quot;)

' Returns filename with specified extension. If more than one *.ini
' file exists, the first file found is returned.
MyFile = Dir(&quot;C:\WINDOWS\*.INI&quot;)

' Call Dir again without arguments to return the next *.INI file in the
' same directory.
MyFile = Dir

' Return first *.TXT file with a set hidden attribute.
MyFile = Dir(&quot;*.TXT&quot;, vbHidden)

' Display the names in C:\ that represent directories.
MyPath = &quot;c:\&quot; ' Set the path.
MyName = Dir(MyPath, vbDirectory) ' Retrieve the first entry.
Do While MyName <> &quot;&quot; ' Start the loop.
' Ignore the current directory and the encompassing directory.
If MyName <> &quot;.&quot; And MyName <> &quot;..&quot; Then
' Use bitwise comparison to make sure MyName is a directory.
If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then
Debug.Print MyName ' Display entry only if it
End If ' it represents a directory.
End If
MyName = Dir ' Get next entry.
Loop

 
Note that the Getattr() function is a better choice than the Dir() function because the latter does not return a &quot;found&quot; indicator is the path is hidden.

If you don't care about hidden files, the DIR function is fine.
 
Function to check for named file

Private Function DoesFileExist(FileName) As Boolean
' check for data file
Dim fs As Variant
Set fs = CreateObject(&quot;scripting.filesystemobject&quot;)

If fs.FileExists(FileName) Then
DoesFileExist = True
Else
DoesFileExist = False
End If
Set fs = Nothing
End Function

to check for folder, use this code
fs.folderexists(&quot;Drive:\Path&quot;)

Chris.
 
I once wrote a function that tried to open the file for a binary read, and used error trapping to decide whether or not the file exists.

In later life I sobered up and used DIR, but my original approach does have the advantage of offering an absolute answer to the question (unless you're networking...)


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top