There could be a time when you need to check a file or folder exists or not. There are actually a different ways to accomplish this task. You could use the Dir Function located in the FileSystem Class, the Windows API, or the FileSystemObject located in the Windows Scripting Host Object Model. I will show how to use the Dir method and the FileSystem Scripting Object to check if a folder/file exits or not.
Using the DIR Function…
This feature is accessible from the VB 6.0 Runtime, so you don’t need to add any references or components. In my experience this method works just fine, but there could be a scenario that it may not work properly for you.
You simply call the Dir function with the path of the file or directory in the parameter. If the functions returns nothing then its not seeing the path you specified and thus the file or directory does not exist.
If Dir("c:\myFile.txt") <> "" Then MsgBox "It Exists!" Else MsgBox "No Go!" End If
That’s all there is to it. As I said, I do not know how this method would work in every scenario, but I’ve seen no problems yet.
Using the Scripting FileSystemObject…
This method is not part of the VB 6.0 runtime. So you will first want to go to the Project menu and click on the References item. Once all of the objects are displayed scroll down till you see – “Windows Script Host Object Model”, checkmark it then click OK.
Next you need to create an instance of the FileSystemObject you just referenced.
Dim f As FileSystemObject Set f = New FileSystemObject
Now you just need to call the available FileExists and FolderExists Functions while passing the path for the file and the path for the directory you want to check.
MsgBox f.FileExists("c:\myFile.txt") MsgBox f.FolderExists("c:\")
Depending on whether the file or folder path you specified exits or not the messagebox should have thrown a True or False message.
That’s all there is to it for checking whether a file exists or if a folder/directory exists. The FileSystemObject method is more elegant and maybe more reliable than using the Dir Function but at the cost of having to add a Reference to the Windows Scripting Object which is not apart of the Visual Basic 6.0 Runtime Library. The Dir method still seems to work ok for me. Both ways appear to be case in-sensitive so you won’t have to worry about the letter casing being exact. IF you know of some other ways please feel free to leave a message with the way you do it. Anyways, Have Fun!