Using Files: Section VI
This section will cover file error handling, and demonstrate how to use error trapping to check the status of files.
Author: Jens G. Balchen

Before You Start

This section will not explain error trapping in general. You should be familiar with the On Error statement and how to use error codes and error messages.

Error Messages

These are the error messages in Visual Basic related to files:

52Bad file name or number
53File not found
54Bad file mode
55File already open
57Device I/O error
58File already exists
59Bad record length
61Disk full
62Input past end of file
63Bad record number
67Too many files
68Device unavailable
70Permission denied
71Disk not ready
74Can't rename with different drive
75Path/File access error
76Path not found

When you try to open a file, any one of these errors can occur, especially the ones concerning file names (Bad file name or number) and file locations (File not found, Path not found). It is important for an application to either check the filenames before it tries to open them, or trap the errors that occure when it opens them.

The error trapping procedures are similar to every other error trapping procedure:

   On Error Goto FileError

   Open "C:\Windows\Non-existing Filename.txt" For Input As #1
   Close #1

   Exit Sub

FileError:

   Select Case Err.Number
      Case 53
      ' Error handling code would go here
      Case 55
      ' Error handling code would go here
   End Select

This is a very crude example, but it demonstrates the principle. Now, when you open a file, you could do one out of two things: Either you decide to trap every error that could occure, or you figure out which errors are more likely to occure and trap them.

With the second approach, there's always the possibility that an unexpected error could crash the application. This is a calculated risk -- creating error handling code for file accesses in 200 different procedures is a large job, especially due to Visual Basic's lack of a global error trapping system.

Checking File Status

The error trapping can be useful if you want to check if a file name is valid or not, and also if you have implemented file locking in your applications.

Here's how to test if a file is locked or not:

Public Function FileLocked(ByVal Filename As StringAs Boolean

Dim fHandle As Integer

   On Error Goto FileError

   fHandle = FreeFile
   Open Filename For Input As #fHandle
   Close #fHandle

   FileLocked = False
   Goto ExitFunction

FileError:

   Select Case Err.Number
      Case 70
         FileLocked = True
      Case Else
      ' An unexpected error. We do not deal with this in this example
   End Select

ExitFunction:

End Function