Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Aug 19, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Testing for a Given File

There are lots of ways to test for whether a given file exists. The most common method is to use the Dir$ function. If Dir$ returns a null string, then the file doesn't exist. Couldn't be simpler, right? If an illegal filespec is tested, an error occurs. This function depends on an error to detect file existence, and rather than using Dir$, it uses Name.
 Function Exists (ByVal FileSpec$) 

Dim TestSpec$ 
Exists = False 
FileSpec = Trim(FileSpec) 

If Right$(FileSpec$, 1) = "\" Or _ 
Right$(FileSpec$, 2) = "\." Or _ 
Right$(FileSpec$, 3) = "\.." Then 
'Obviously passed a directory not a file! 
'Avoid *MAJOR BUG* with Name function by not 
'trying to rename the root directory. 
Exit Function 
End If 

On Local Error Resume Next 
Name FileSpec As FileSpec 

Select Case Err 
Case 5 'Illegal Function Call 
Case 53 'File Not Found 
Case 58 'File Already Exists (Maybe!) 
TestSpec = Dir$(FileSpec) 
If Len(TestSpec) Then Exists = True 
Case 64 'Bad Filename 
Case 68 'Device Unavailable 
Case 74 'Can't rename with different drive 
Case 71 'Disk Not Ready 
Case 75 'Path/File Access Error 
Case 76 'Path Not Found 
Case Else 
MsgBox "Unexpected Error " & Err & " _ 
in Exists(): " & Error$ 
End Select 
End Function 
Trying to rename a file to its current name generates error 58 -- File Already Exists. If the file doesn't exist, you get error 53 -- File Not Found. These errors really tell you something, don't they? There are a number of other possible errors, however, each revealing something about the filespec. The Exists function lists all the errors and their causes that I've been able to track down. Because a directory name generates the same error as a file when attempting to rename it to itself, I call Dir$ into action to confirm that a file and not a directory was passed as the filespec. As presented, Exists is an experimental function. You'd obviously want to trim it down if you want only the final answer. By modifying this function slightly, you could also return the cause of the error, which could help you help the user correct the situation. Also, by passing many different filespecs, you might discover new ways your users could devise to break your program.
Karl E.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date