如何读取文件夹中的文件?

时间:2015-02-03 12:33:47

标签: vb.net

我正在尝试让我的应用程序检查folderbrowserdialogs selectedpath中的文件夹,然后获取这些文件,但它不起作用我已经尝试了下面列出的两种方法。第二种方式给了我一个错误:(表达式是char类型,它不是集合类型)

    For Each folder In FileBrowserDialog.SelectedPath
        Dim counter As  _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
            counter = My.Computer.FileSystem.GetFiles(folder)
            Label1.Text = counter.Count.ToString
        Next



For Each folder In FileBrowserDialog.SelectedPath
        Dim counter As  _
System.Collections.ObjectModel.ReadOnlyCollection(Of String)
For Each foundfile In folder
            counter = My.Computer.FileSystem.GetFiles(foundfile)
            Label1.Text = counter.Count.ToString
        Next

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

FolderBrowserDialog1.SelectedPath将返回用户在对话框中选择的路径。你仍然需要编写代码来获取文件。可能不需要获取文件夹,然后文件。 Net有办法为你做到这一点:

FolderBrowserDialog1.ShowDialog()
Dim myPath As String = FolderBrowserDialog1.SelectedPath

' get all files for a folder
Dim files = Directory.GetFiles(myPath)

' get all files for all sub folders
Dim files = Directory.GetFiles(myPath, "*.*",
         System.IO.SearchOption.AllDirectories)

' get certain file types for folder and subs
Dim files = Directory.GetFiles(myPath, "*.jpg",
         System.IO.SearchOption.AllDirectories)

您也无法简单地将结果分配给ReadOnlyCollection,因为它们是ReadOnly。需要使用完整列表创建/实例化集合:

Dim counter As new ReadOnlyCollection(Of String)(files)