VB 6 如何快速检查网络上的文件是否存在

3
以下代码:
    If FileExists(XCustPath + "XCust.dat") Then
        XCustRun
    End If

并且这段代码:

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指的是包含XCust.dat文件的映射网络位置。

但在此行中:

lRetVal = OpenFile(Fname, OfSt, OF_EXIST)

这个程序需要检查网络中的文件是否存在,但是这个过程非常缓慢,会导致程序锁定20-30秒。由于这是一个旧的销售应用程序,因此需要在不到1秒钟的时间内检查文件是否存在。有没有办法强制让代码在一秒钟后超时?如果文件存在,则程序可以顺利运行。或者有没有一种非常快速的方法来检查网络上的文件是否存在?


文件是否在宕机的服务器上?此外,如果文件存在,您需要关闭它。 - user253751
3个回答

4

这样会更快:

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
if fso.fileexists(Fname) ...

3

试试这个...

Public Function FileExists(ByVal Fname As String) As Boolean
        FileExists = iif (Dir(Fname)<>"", true, false)
End Function

+1 简单明了,虽然不需要使用iif,因为Dir(Fname)<>""是一个布尔表达式,但要注意不存在的UNC路径会生成运行时错误(与不存在的驱动器号不同)。 - Alex K.
这将重置当前的 Dir 枚举,并且不能在使用 sNext = Dir(sMask): Do While LenB(sNext) <> 0 ... sNext = Dir : Loop 循环文件夹时使用。 - wqw

1

最快的方法是检查文件属性(由于传统原因)。我正在使用像这样的API函数。

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

你可以使用VB的GetAttr和错误处理程序来重写它,如下所示。
Public Function FileExists(sFile As String) As Boolean
    On Error GoTo QH
    GetAttr sFile
    FileExists = True
QH:
End Function

我更喜欢第一个版本,因为我在所有项目中都保持在所有错误处中断的设置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接