vb中检测文件是否存在

来源:互联网 发布:ubuntu mysql数据库 编辑:程序博客网 时间:2024/06/11 15:32

1。利用DIR
      If dir(fname)="" then '文件不存在

字串3

 

2。利用 api
在某些场合,我们需要确定特定目录下特定文件是否存在。VB自带的DIR函数可以查找符合条件的文件。这里介绍一种较为简单的方法。
API函数的 SHFileExists 的功能,从其名字来看,应该是 Search File Exists,亦即查找存在的文件。用它来检测文件存在与否是很容易的。试看下面的例子。

字串6

 

在标准EXE工程放置两个文本框和一个按钮,输入如下代码: 字串2

Private Declare Function SHFileExists Lib "shell32" Alias "#45" (ByVal szPath As String) As Long 字串6

Private Sub Command1_Click()
Dim i As Integer
i = Str$(SHFileExists(Text1.Text))
If i = 0 Then 'Str$值只有两种可能,0或者1
Text2.Text = "文件不存在"
Else
Text2 = "文件存在"
End If
End Sub 字串2

按F5运行/doc/">程序,在 Text1 输入要查找的文件的驱动器名、路径和名称,然后点击按钮,Text2会报告文件是否存在。
值得一提的是,SHFileExists 函数支持对任何文件的查找,同时也支持对文件夹的查找。

字串6

 

3。Public Declare Function MakeSureDirectoryPathExists Lib "imagehlp.dll" (ByVal DirPath As String) As Long '创建多层目录
用法:
MakeSureDirectoryPathExists "c:/this/is/a/test/directory/" 字串5

4。不用FSO对象 VB直接检测文件是否存在 

字串7

 


'不用FSO对象   VB直接检测文件是否存在,当使用fso的/doc/">程序需要带runtime文件。' 这样/doc/">程序变成多个文件,很多操作系统本身并没有这个文件。'有些人使用Dir("文件名")判断,但是当主调函数也正在用dir并且后续使用没有结束时就会出错。Public Function FileExists(ByVal File As String) As Boolean
                     On Error Resume Next
                     If (GetAttr(File) And vbDirectory) = False Then FileExists = True
                     If err Then FileExists = False: err.Clear
         End Function
         Function FolderExists(ByVal Folder As String) As Boolean
                     On Error Resume Next

字串7

                     If GetAttr(Folder) And vbDirectory Then FolderExists = True
                     If err Then FolderExists = False: err.Clear
         End Function
上面都是用的vbDirectory=16 不要认为写错了 字串4