vb.net 教程 4-2 目录操作 DirectoryInfo 4

本节谈谈如何获得某个目录下的子目录和文件
当然,等到讲完了目录操作后,我将会举个类似于资源管理器的例子。

窗体设计界面如下:

列出子目录:
    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 教程 目录

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...