Testing for a Given File

There are lots of ways to test for whether a given file exists. Themost common method is to use the Dir$ function. If Dir$ returns a nullstring, then the file doesn’t exist. Couldn’t be simpler, right? If anillegal filespec is tested, an error occurs. This function dependson an error to detect file existence, and rather than using Dir$, it usesName.

 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? Thereare a number of other possible errors, however, each revealing somethingabout the filespec. The Exists function lists all the errors and theircauses that I’ve been able to track down. Because a directory name generatesthe same error as a file when attempting to rename it to itself, I callDir$ into action to confirm that a file and not a directory was passedas the filespec. As presented, Exists is an experimental function. You’d obviously wantto trim it down if you want only the final answer. By modifying this functionslightly, you could also return the cause of the error, which could helpyou help the user correct the situation. Also, by passing many differentfilespecs, you might discover new ways your users could devise to breakyour program.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: