版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。 本节谈谈如何获得某个目录下的子目录和文件,
当然,等到讲完了目录操作后,我将会举个类似于资源管理器的例子。
窗体设计界面如下:
列出子目录:
Private Sub btnSubFolders_Click(sender As Object, e As EventArgs) Handles btnSubFolders.Click Dim di As New DirectoryInfo("c:\windows") If di.Exists = False Then Exit Sub txtFolderInfo.Text = "" For Each folderinfo As DirectoryInfo In di.GetDirectories txtFolderInfo.Text &= folderinfo.Name & ControlChars.CrLf Next End Sub为简化操作,直接使用的Windows目录。
列出目录下的文件:
Private Sub btnFiles_Click(sender As Object, e As EventArgs) Handles btnFiles.Click Dim di As New DirectoryInfo("c:\windows") If di.Exists = False Then Exit Sub txtFolderInfo.Text = "" For Each finfo As FileInfo In di.GetFiles txtFolderInfo.Text &= finfo.Name & ControlChars.CrLf Next End Sub提前用了点FileInfo的知识。
列出所有:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim di As New DirectoryInfo("c:\windows") If di.Exists = False Then Exit Sub Dim fsType As String txtFolderInfo.Text = "" For Each fsinfo As FileSystemInfo In di.GetFileSystemInfos If (fsinfo.Attributes And FileAttribute.Directory) = FileAttribute.Directory Then fsType = "目录" Else fsType = "文件" txtFolderInfo.Text &= fsType & " " & fsinfo.Name & ControlChars.CrLf Next End Sub其实,DirectoryInfo和FileInfo都是继承于FileSystemInfo,很多属性和方法都来自FileSystemInfo。
运行时如图:
学习更多vb.net知识,请参看 vb.net 教程 目录