方法一: 方法二: 1。利用DIR 2。利用 api 在某些场合,我们需要确定特定目录下特定文件是否存在。VB自带的DIR函数可以查找符合条件的文件。这里介绍一种较为简单的方法。 API函数的 SHFileExists 的功能,从其名字来看,应该是 Search File Exists,亦即查找存在的文件。用它来检测文件存在与否是很容易的。试看下面的例子。 在标准EXE工程放置两个文本框和一个按钮,输入如下代码: Private Declare Function SHFileExists Lib "shell32" Alias "#45" (ByVal szPath As String) As Long 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 按F5运行程序,在 Text1 输入要查找的文件的驱动器名、路径和名称,然后点击按钮,Text2会报告文件是否存在。 值得一提的是,SHFileExists 函数支持对任何文件的查找,同时也支持对文件夹的查找。 3。Public Declare Function MakeSureDirectoryPathExists Lib "imagehlp.dll" (ByVal DirPath As String) As Long '创建多层目录 用法: MakeSureDirectoryPathExists "c:/this/is/a/test/directory/" 4。不用FSO对象 VB直接检测文件是否存在 '不用FSO对象 VB直接检测文件是否存在,当使用fso的程序需要带runtime文件。' 这样程序变成多个文件,很多操作系统本身并没有这个文件。'有些人使用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 If GetAttr(Folder) And vbDirectory Then FolderExists = True If err Then FolderExists = False: err.Clear End Function 上面都是用的vbDirectory=16 不要认为写错了 1。利用DIR 2。利用 api 在某些场合,我们需要确定特定目录下特定文件是否存在。VB自带的DIR函数可以查找符合条件的文件。这里介绍一种较为简单的方法。 API函数的 SHFileExists 的功能,从其名字来看,应该是 Search File Exists,亦即查找存在的文件。用它来检测文件存在与否是很容易的。试看下面的例子。 在标准EXE工程放置两个文本框和一个按钮,输入如下代码: Private Declare Function SHFileExists Lib "shell32" Alias "#45" (ByVal szPath As String) As Long 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 按F5运行程序,在 Text1 输入要查找的文件的驱动器名、路径和名称,然后点击按钮,Text2会报告文件是否存在。 值得一提的是,SHFileExists 函数支持对任何文件的查找,同时也支持对文件夹的查找。 3。Public Declare Function MakeSureDirectoryPathExists Lib "imagehlp.dll" (ByVal DirPath As String) As Long '创建多层目录 用法: MakeSureDirectoryPathExists "c:/this/is/a/test/directory/" 4。不用FSO对象 VB直接检测文件是否存在 '不用FSO对象 VB直接检测文件是否存在,当使用fso的程序需要带runtime文件。' 这样程序变成多个文件,很多操作系统本身并没有这个文件。'有些人使用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 If GetAttr(Folder) And vbDirectory Then FolderExists = True If err Then FolderExists = False: err.Clear End Function 上面都是用的vbDirectory=16 不要认为写错了 |
|
来自: 百眼通 > 《03VB和VB.NET-113》