搜索文件夹和特定文件类型的所有子文件夹

时间:2014-08-02 14:21:59

标签: vb.net search

我使用下面的代码将所有.txt文件存储在数组中的特定路径中。

Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt", SearchOption.AllDirectories)

folderDIR是我要搜索的文件夹的目录。但是这种方法似乎不起作用。它将所有.txt文件放在当前位置,但不考虑子文件夹。

谁能告诉我我做错了什么?或者有更好的方法吗?

谢谢。

1 个答案:

答案 0 :(得分:-1)

http://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx

' For Directory.GetFiles and Directory.GetDirectories 
' For File.Exists, Directory.Exists  
    Imports System
Imports System.IO
Imports System.Collections

Public Class RecursiveFileProcessor

    Public Overloads Shared Sub Main(ByVal args() As String)
        Dim path As String 
        For Each path In args
            If File.Exists(path) Then 
                ' This path is a file.
                ProcessFile(path)
            Else 
                If Directory.Exists(path) Then 
                    ' This path is a directory.
                    ProcessDirectory(path)
                Else
                    Console.WriteLine("{0} is not a valid file or directory.", path)
                End If 
            End If 
        Next path
    End Sub 'Main


    ' Process all files in the directory passed in, recurse on any directories  
    ' that are found, and process the files they contain. 
    Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
        Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
        ' Process the list of files found in the directory. 
        Dim fileName As String 
        For Each fileName In fileEntries
            ProcessFile(fileName)

        Next fileName
        Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
        ' Recurse into subdirectories of this directory. 
        Dim subdirectory As String 
        For Each subdirectory In subdirectoryEntries
            ProcessDirectory(subdirectory)
        Next subdirectory

    End Sub 'ProcessDirectory

    ' Insert logic for processing found files here. 
    Public Shared Sub ProcessFile(ByVal path As String)
        Console.WriteLine("Processed file '{0}'.", path)
    End Sub 'ProcessFile
End Class 'RecursiveFileProcessor