HOWTO: Determine If a File Exists by Using DIR$

ID: Q112674


The information in this article applies to:


SUMMARY

Visual Basic does not have any built-in functions that tell if a file exists or not. This article demonstrates how to find out if a file exists or not by using a Visual Basic program.


MORE INFORMATION

There are two different methods you can use to determine if a file exists:

Step-by-Step Example

This example show how to check for the existence of a file by using the DIR$ function.
  1. Start a new project in Visual Basic. Form1 is created by default.


  2. Add a CommandButton (Command1) to Form1.


  3. Place the following code in the Command1_Click Event:
    
          Sub Command1_Click()
             Dim TheFile as String
             Dim Results as String
    
             TheFile = "C:\AUTOEXEC.BAT"
             Results = Dir$(TheFile)
    
             If Results  = "" Then
                MsgBox "File Doesn't Exist!"
             Else
                MsgBox "File does Exist!"
             End If
          End Sub
     


  4. Run the program, and click the Command1 button.


  5. Stop the program and make the TheFile variable point to a file that doesn't exist.


  6. Run the program again, and click the Command1 button.



Error in Visual Basic Help File Code

Please note that there is an error in the sample that is provided with the Visual Basic 3.0 Help file (NOTE: This only applies to Visual Basic 3.0, the samples provided with Visual Basic 4.0 and 5.0 are correct). The first line of the following If block is incorrect:

      If GetAttr(Path + DirName) And ATTR_DIRECTORY = ATTR_DIRECTORY Then
         If (Count Mod 10) = 0 Then
            ReDim Preserve D(Count + 10)  ' Resize the array.
         End If
         Count = Count + 1  ' Increment counter.
         D(Count) = DirName
      End If 

Here's the correct version (only difference is the first line):

      If GetAttr(path + DirName) = ATTR_DIRECTORY Then
         If (Count Mod 10) = 0 Then
            ReDim Preserve D(Count + 10) ' Resize the array.
         End If
         Count = Count + 1 ' Increment counter.
         D(Count) = DirName
      End If 


REFERENCES

For more information, see the Programmer's Reference, File Manipulation and the DIR/DIR$ commands.

Additional query words: existence


Keywords          : kbprg kbVBp400 kbVBp500 kbhowto PrgOther VB4WIN 
Version           : 3.0 4.0 5.0
Platform          : NT WINDOWS 
Issue type        : kbhowto 

Last Reviewed: June 1, 1999