PDA

Click to See Complete Forum and Search --> : Open function


Rick H
Jan 18th, 2000, 03:20 PM
How can I check if I a file exists when using the open function?

e.g

Open "c:\filename.txt" For Input As #1

if the file does`nt exist a "run-time" error window occurs. Is there anyway to stop this?
Either a

exists = doesfileexist("C\filename.txt")

or an extension of the Open function?

Thanks in advance.

Maartin
Jan 18th, 2000, 03:57 PM
The only true VB way to check if a file exists is to use the dir function.

The Open function will create the file for you if it does not exist.

So to check, use the following:

If Dir("c:\filename.txt") <> "" Then
'|File does exist
Else
'|File does not exist
End If

I don't know where your runtime error comes from; it might be syntax error or something like that.
If you want to, send me the code and I’ll have a look at it for you. Or else I will create you a small sample.

Just let me know.

Hope it helps.

-----------------------
Maartin
dinamite@onwe.co.za
-----------------------


[This message has been edited by Maartin (edited 01-19-2000).]

venkatraman_r
Jan 18th, 2000, 04:06 PM
Hi,

You can use this:

if Len(Dir(Filename)>0then
msgbox "File does not exist"
else
''do something
end if.

First you have to get the filename in a variable and try this.

Hope it helps. :) Good luck.

------------------
Regards,

Venkat

venkatraman_r@hotmail.com
ICQ: 45714766
http://venkat.iscool.net

Rick H
Jan 18th, 2000, 04:09 PM
Cheers chaps, that works a treat

[This message has been edited by Rick H (edited 01-19-2000).]

ivyl
Jan 18th, 2000, 04:50 PM
Just a quick comment. First of all Rick H got the error because he was trying to open a file that didn't exist. Second, you can get errors if you try to use Dir() together with the filename AND the full path, if the path doesn't exist. You can check if a path exist by using Dir(path$, vbDirectory).

Crazy D
Jan 18th, 2000, 05:15 PM
Yes, but you can also just easily trap the error...

On error goto errhandler
Dim iFile As Integer
iFile = FreeFile
Open PathAndFileName For Input As #iFile
' do something
Close #iFile

Exit Sub ' or function
errhandler:
' trap the several errors that can occur here...
' don't forget to close the file if another error occured then "does not exist"
msgbox Err.Number & " - " & Err.Description