vb.net编程查找搜索指定目录下面的所有文件和其子目录下的文件,方法如下:
锡林浩特ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联建站的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!
''=============================================
''名称: FindPath
''作用: 查找搜索指定目录下面的所有文件和其子目录下的文件
''参数:strPath 要查找的目录,
''strFiles 用于存查找结果的缓冲区,String 类型的动态数组,调用时事先初始化, 如Redim strFiles(0)
''FileCount 用于返回文件个数
''=============================================
Public Sub FindPath(ByVal strPath As String, strFiles() As String, FileCount As Long)
Dim strDirs() As String
Dim strResult As String
Dim FileLimit As Long
Dim dirLimit As Long
Dim dirCount As Long
Dim I As Long
FileLimit = UBound(strFiles) + 1
dirLimit = 0
If Right$(strPath, 1) "/" Then strPath = strPath "/"
strResult = Dir(strPath, vbDirectory + vbSystem + vbReadOnly + vbHidden + vbNormal + vbArchive)
Do While Len(strResult) 0
If strResult "." And strResult ".." Then
If (GetAttr(strPath strResult) And vbDirectory) vbDirectory Then
If FileCount = FileLimit Then
ReDim Preserve strFiles(FileLimit + 10)
FileLimit = FileLimit + 10
End If
strFiles(FileCount) = strPath strResult
FileCount = FileCount + 1
Else
If dirCount = dirLimit Then
ReDim Preserve strDirs(dirLimit + 10)
dirLimit = dirLimit + 10
End If
strDirs(dirCount) = strPath strResult
dirCount = dirCount + 1
End If
End If
strResult = Dir(, vbDirectory + vbSystem + vbReadOnly + vbHidden + vbNormal + vbArchive)
Loop
For I = 0 To dirCount - 1
Call FindPath(strDirs(I), strFiles, FileCount)
Next I
End Sub
步骤如下:
窗体上添加2个列表框,一个按钮:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MyDir As String = "C:\123"
'搜索并显示子文件夹
ListBox1.Items.Clear()
For Each MySubDir As String In System.IO.Directory.GetDirectories(MyDir)
ListBox1.Items.Add(MySubDir)
Next
'搜索并显示文件
ListBox2.Items.Clear()
For Each MyFile As String In System.IO.Directory.GetFiles(MyDir)
ListBox2.Items.Add(MyFile)
Next
End Sub
End Class
思路:
1,使用ListBox1控件来存放搜索到的文件名,然后ListBox1.SelectedItem就可以返回选中项的文本;
2,利用获得的选中项文本(即文件与路径),使用打开文本文件的方法,读取内容显示在文本框里。