How would I test to see if a file exists before I try to open it??
Printable View
How would I test to see if a file exists before I try to open it??
[Edited by sp007 on 08-29-2000 at 10:48 PM]Code:If Dir("C:\Windows\file.txt", vbHidden) = "" Then
Open "C:\Windows\file.txt" For Output As #1
print #1, variable
Close #1
Else
Open "C:\Windows\file.txt" For Input As #1
Line Input #1, variable
Close #1
End If
Go to this site -
http://www.planet-source-code.com/xq...s/ShowCode.htm
An easier why is to use the filesystemobject
you'll have to reference the Microsoft Scripting Runtime thing first
Private Sub cmdCheckForFile_Click()
Dim fs
Set fs = New Scripting.FileSystemObject
Exists = fs.FileExists(fs.BuildPath(App.Path, "YourFileHere.txt"))
'Exists is now a boolean variable with the results T/F of
'if the file exists or not
MsgBox Exists
End sub
This method is returning "false" whether the file is there or not...any thoughts??
Try this:
Code:If Dir("C:\file.txt") <> "" Then
Open "C:\file.txt" For Input As #1
Text1.Text = Input$(LOF(1), 1)
Close #1
Else
Msgbox "File does not exist!", vbCritical
End If
Be careful with the code above that you used. you'll notice that it had app.path etc so the position of the file was preset (which is likely why you never found a file you knew was there).Quote:
Originally posted by crptcblade
This method is returning "false" whether the file is there or not...any thoughts??
try it like this
Code:
Function ReportFileStatus(filespec)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = filespec & " exists."
Else
msg = filespec & " doesn't exist."
End If
ReportFileStatus = msg
End Function
Function FileExists (p As String) As Long
If Dir (p) <> " " Then
FileExists = conSuccess ' Return a constant
' indicating the
Else ' file exists.
FileExists = conFailure ' Return failure
' constant.
End If
End Function
Dim ResultValue As Long
ResultValue = FileExists ("C:\Testfile.txt")
If ResultValue = conFailure Then
.
. ' Handle the error.
.
Else
.
. ' Proceed with the program.
.
End If
Function FileExists (filename) As Boolean
FileExists = (Dir(filename) <> "")
End Function
'Returns true if file exists, false if it doesn't