窗体上添加一个文本框,一个列表框,一个按钮:
专注于为中小企业提供网站设计、成都网站制作服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业泗水免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千多家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
代码如下:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim MyDir As String = "C:\123"
Dim MyFilter As String = "*" TextBox1.Text "*"
ListBox1.Items.Clear()
For Each MyFile As String In System.IO.Directory.GetFiles(MyDir, MyFilter)
ListBox1.Items.Add(MyFile)
Next
End Sub
vb.net编程查找搜索指定目录下面的所有文件和其子目录下的文件,方法如下:
''=============================================
''名称: 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
思路:
1,使用ListBox1控件来存放搜索到的文件名,然后ListBox1.SelectedItem就可以返回选中项的文本;
2,利用获得的选中项文本(即文件与路径),使用打开文本文件的方法,读取内容显示在文本框里。
步骤如下:
窗体上添加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