问题
The following code:
If FileExists(XCustPath + "XCust.dat") Then
XCustRun
End If
and this code:
Public Function FileExists(ByVal Fname As String) As Boolean
Dim lRetVal As Long
Dim OfSt As OFSTRUCT
lRetVal = OpenFile(Fname, OfSt, OF_EXIST)
If lRetVal <> HFILE_ERROR Then
FileExists = True
Else
FileExists = False
End If
End Function
XCustPath points to a mapped network location with the file XCust.dat inside it.
But on the line:
lRetVal = OpenFile(Fname, OfSt, OF_EXIST)
It takes forever and locks up my program for 20-30 seconds. It needs to check if this file exists on the network in less than 1 second as it is for a legacy point of sale application. Is there anyway I can force it to timeout the line of code if it takes longer than a second? If it does exist it runs smoothly and perfect. Or a VERY quick way of checking if a file on the network exists?
回答1:
This should be faster:
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
if fso.fileexists(Fname) ...
回答2:
Try This ....
Public Function FileExists(ByVal Fname As String) As Boolean
FileExists = iif (Dir(Fname)<>"", true, false)
End Function
回答3:
Fastest will be to check the file attributes (for legacy reasons). I'm using API
function like this
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Public Function FileExists(sFile As String) As Boolean
FileExists = (GetFileAttributes(sFile) <> -1) ' INVALID_FILE_ATTRIBUTES
End Function
You can rewrite it with VB's GetAttr
and an error handler like this
Public Function FileExists(sFile As String) As Boolean
On Error GoTo QH
GetAttr sFile
FileExists = True
QH:
End Function
I prefer the first version as I keep Break on All Errors
setting on for all my projects.
来源:https://stackoverflow.com/questions/17848923/vb-6-checking-if-a-file-on-the-network-exists-takes-too-long